参考官网:https://mybatis.org/mybatis-3/zh/index.html
1.搭建数据库环境
CREATE DATABASE `mybatis`; USE `mybatis`; DROP TABLE IF EXISTS `user`; CREATE TABLE `user` ( `id` int(20) NOT NULL, `name` varchar(30) DEFAULT NULL, `pwd` varchar(30) DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; insert into `user`(`id`,`name`,`pwd`) values (1,'奔奔','123456'),(2,'张三','123456'),(3,'李四','123456');
2.导入MyBatis相关jar包
<dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.5.2</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.47</version> </dependency>
3.引入MyBatis所需要的db.properties文件
下面这个是固定的文件,可以复用
driver=com.mysql.cj.jdbc.Driver url=jdbc:mysql://localhost:3306/mybaits?useSSL=true&useUnicode=true&\ characterEncoding=UTF-8&serverTimezone=UTC username=root password=123456
4.编写MyBatis核心配置文件
这个文件在配置好以后,一般很少有改变
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd"> <configuration> <!--引入外部配置文件--> <properties resource="db.properties"/> <!--给实体类写别名--> <typeAliases> <package name="com.ben.pojo"/> </typeAliases> <environments default="development"> <environment id="development"> <transactionManager type="JDBC"/> <dataSource type="POOLED"> <property name="driver" value="${driver}"/> <property name="url" value="${url}"/> <property name="username" value="${username}"/> <property name="password" value="${password}"/> </dataSource> </environment> </environments> <mappers> <mapper resource="UserMapper.xml"/> </mappers> </configuration>
5.创建实体类User
package com.ben.pojo; public class User { private int id; private String name; private String pwd; public User() { } public User(int id, String name, String pwd) { this.id = id; this.name = name; this.pwd = pwd; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getPwd() { return pwd; } public void setPwd(String pwd) { this.pwd = pwd; } @Override public String toString() { return "User{" + "id=" + id + ", name='" + name + '\'' + ", pwd='" + pwd + '\'' + '}'; } }
6.编写MyBatis工具类
import org.apache.ibatis.io.Resources; import org.apache.ibatis.session.SqlSession; import org.apache.ibatis.session.SqlSessionFactory; import org.apache.ibatis.session.SqlSessionFactoryBuilder; import java.io.IOException; import java.io.InputStream; public class MybatisUtils { private static SqlSessionFactory sqlSessionFactory; static { try { String resource = "mybatis-config.xml"; InputStream inputStream = Resources.getResourceAsStream(resource); sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream); } catch (IOException e) { e.printStackTrace(); } } //获取SqlSession连接 public static SqlSession getSession(){ return sqlSessionFactory.openSession(); } }
7.编写Mapper接口类(相当于dao层的接口)
package com.ben.dao; import com.ben.pojo.User; import java.util.List; public interface UserMapper { //查询全部用户 List<User> getUserList(); //根据id查询用户 User getUserById(int id);//里面的参数就是sql语句中要填写的参数,见test类 //insert一个用户 int addUser(User user); //修改用户 int updateUser(User user); //删除一个用户 int deleteUser(int id); }
8.编写Mapper.xml配置文件
namespace 十分重要,不能写错!
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="com.ben.dao.UserMapper"> <select id="getUserList" resultType="User"> select * from mybaits.user </select> <select id="getUserById" parameterType="int" resultType="com.ben.pojo.User"> select* from mybaits.user where id=#{id} </select> <insert id="addUser" parameterType="com.ben.pojo.User"> insert into mybaits.user(id,name,pwd) values(#{id},#{name},#{pwd}) </insert> <update id="updateUser" parameterType="com.ben.pojo.User"> update mybaits.user set name=#{name},pwd=#{pwd} where id=#{id}; </update> <delete id="deleteUser" parameterType="int"> delete from mybaits.user where id=#{id}; </delete> </mapper>
9.编写测试类
package dao; import com.ben.dao.UserMapper; import com.ben.pojo.User; import com.ben.utils.MybatisUtils; import org.apache.ibatis.session.SqlSession; import org.junit.Test; import java.util.List; public class UserDaoTest { @Test public void test(){ SqlSession sqlSession = MybatisUtils.getSqlSession(); UserMapper userDao = sqlSession.getMapper(UserMapper.class); List<User> userList = userDao.getUserList(); for (User user : userList) { System.out.println(user); } sqlSession.close(); } @Test public void testGetUserById(){ SqlSession sqlSession = MybatisUtils.getSqlSession(); UserMapper mapper = sqlSession.getMapper(UserMapper.class); User user = mapper.getUserById(1); System.out.println(user); sqlSession.close(); } @Test public void TestAddUser(){ SqlSession sqlSession = MybatisUtils.getSqlSession(); UserMapper mapper = sqlSession.getMapper(UserMapper.class); int result = mapper.addUser(new User(3, "李四", "123123")); System.out.println(result); sqlSession.commit(); sqlSession.close(); } @Test public void testUpdateUser(){ SqlSession sqlSession = MybatisUtils.getSqlSession(); UserMapper mapper = sqlSession.getMapper(UserMapper.class); mapper.updateUser(new User(3,"王二麻","123123")); sqlSession.commit(); sqlSession.close(); } @Test public void testDeleteUser(){ SqlSession sqlSession = MybatisUtils.getSqlSession(); UserMapper mapper = sqlSession.getMapper(UserMapper.class); mapper.deleteUser(3); sqlSession.commit(); sqlSession.close(); } }
(preference:kuangshenshuo)