导入依赖 创建一个父项目,导入依赖
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 <dependency > <groupId > mysql</groupId > <artifactId > mysql-connector-java</artifactId > <version > 8.0.21</version > </dependency > <dependency > <groupId > org.mybatis</groupId > <artifactId > mybatis</artifactId > <version > 3.5.2</version > </dependency > <dependency > <groupId > junit</groupId > <artifactId > junit</artifactId > <version > 4.13</version > </dependency >
MyBatis核心配置文件 在resource文件夹下创建核心配置文件,在这个文件下可以配置环境(数据源)、注册mapper、设置类别名等等。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 <?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 > <environments default ="development" > <environment id ="development" > <transactionManager type ="JDBC" /> <dataSource type ="POOLED" > <property name ="driver" value ="com.mysql.cj.jdbc.Driver" /> <property name ="url" value ="jdbc:mysql://localhost:3306/mybatis?useSSL=true& useUnicode=true& characterEncoding=UTF-8" /> <property name ="username" value ="root" /> <property name ="password" value ="123456" /> </dataSource > </environment > </environments > <mappers > <mapper resource ="com/muchlab/mapper/UserMapper.xml" /> </mappers > </configuration >
读取MyBatis核心配置文件 在读取配置文件前,先介绍三个关键的MyBatis类:
SqlSessionFactoryBuilder
:通过读取配置文件,来创建SqlSessionFactory,这里使用了建造者模式,一旦创建了 SqlSessionFactory,就不再需要它了。 因此 SqlSessionFactoryBuilder 实例的最佳作用域是方法作用域(也就是局部方法变量)。但最好还是不要一直保留着它,以保证所有的 XML 解析资源可以被释放给更重要的事情。
SqlSessionFactory
:SqlSessionFactory 一旦被创建就应该在应用的运行期间一直存在,最好不要去释放它或重新创建一个新的实例,最简单的就是使用单例模式或者静态单例模式。
SqlSession
:每个线程都应该有它自己的 SqlSession 实例。SqlSession 的实例不是线程安全的,因此是不能被共享的,所以它的最佳的作用域是请求或方法作用域。换句话说,每次收到 HTTP 请求,就可以打开一个 SqlSession,返回一个响应后,就关闭它。 这个关闭操作很重要,为了确保每次都能执行关闭操作,你应该把这个关闭操作放到 finally 块中或使用try语法来释放该资源。
创建一个工具类,用来返回SqlSession实例
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 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(); } } public static SqlSession getSqlSession () { return sqlSessionFactory.openSession(); } }
创建实体类和Mapper接口 Mapper接口就相当于Dao接口或Repository接口,是外界用来操作数据库的接口
1 2 3 4 5 6 7 8 9 10 11 12 13 14 @Data @AllArgsConstructor @NoArgsConstructor @ToString public class User { private int id; private String name; private String pwd; } public interface UserMapper { List<User> getAll () ; }
创建对应的Mapper.xml 每一个Mapper接口都应该对应一个Mapper.xml文件,该文件是用来解释Mapper接口中方法对应的sql操作,文件里的具体细节请参考官方文档
1 2 3 4 5 6 7 8 9 <?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.muchlab.mapper.UserMapper" > <select id ="getAll" resultType ="com.muchlab.entity.User" > select * from user </select > </mapper >
编写测试类 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 public class UserMapperTest { @Test public void test () { try (SqlSession sqlSession = MybatisUtils.getSqlSession()){ UserMapper mapper = sqlSession.getMapper(UserMapper.class ) ; List<User> all = mapper.getAll(); all.forEach(c->{ System.out.println(c); }); List<User> userlist = sqlSession.selectList("com.muchlab.mapper.UserMapper.getAll" ); userlist.forEach(c->{ System.out.println(c); }); } } }
遇到的问题
Mapper接口定义后,必须在核心配置文件中注册Mapper.xml
资源过滤问题,程序运行后会生成目标文件,因为编译后默认只包含.class文件,如果没配置资源过滤,在target文件夹中会找不到Mapper.xml文件,在pom文件中添加下面代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 <build > <resources > <resource > <directory > src/main/java</directory > <includes > <include > **/*.properties</include > <include > **/*.xml</include > </includes > <filtering > false</filtering > </resource > <resource > <directory > src/main/resources</directory > <includes > <include > **/*.properties</include > <include > **/*.xml</include > </includes > <filtering > false</filtering > </resource > </resources > </build >
select、insert、update、delete
id:对应于Mapper接口中的方法名
resultType:接口中方法的返回类型
parameterType:接口中方法的传入参数类型
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 <?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.muchlab.mapper.UserMapper" > <insert id ="addUser" parameterType ="com.muchlab.entity.User" > insert into user (id, name, pwd) values (#{id}, #{name}, #{pwd}); </insert > <update id ="updateUser" parameterType ="com.muchlab.entity.User" > update user set name=#{name}, pwd=#{pwd} where id=#{id} ; </update > <delete id ="deleteUser" parameterType ="int" > delete from user where id=#{id} </delete > <select id ="getAll" resultType ="com.muchlab.entity.User" > select * from user </select > <select id ="getById" resultType ="com.muchlab.entity.User" parameterType ="int" > select * from user alias where alias.id = #{id}; </select > </mapper >
插入、更新、删除需要执行commit方法,执行commit方法才会把数据提交到数据库中。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 public interface UserMapper { List<User> getAll () ; User getById (int id) ; int addUser (User user) ; int updateUser (User user) ; int deleteUser (int id) ; } public class UserMapperTest { @Test public void getAll () { try (SqlSession sqlSession = MybatisUtils.getSqlSession()){ UserMapper mapper = sqlSession.getMapper(UserMapper.class ) ; List<User> all = mapper.getAll(); all.forEach(c->{ System.out.println(c); }); List<User> userlist = sqlSession.selectList("com.muchlab.mapper.UserMapper.getAll" ); userlist.forEach(c->{ System.out.println(c); }); } } @Test public void getById () { try (SqlSession sqlSession = MybatisUtils.getSqlSession()){ UserMapper mapper = sqlSession.getMapper(UserMapper.class ) ; User user = mapper.getById(1 ); System.out.println(user); } } @Test public void addUser () { try (SqlSession sqlSession = MybatisUtils.getSqlSession()){ UserMapper mapper = sqlSession.getMapper(UserMapper.class ) ; int result = mapper.addUser(new User(6 ,"John Lennon" , "12345" )); if (result>0 ){ System.out.println("插入成功" ); } List<User> all = mapper.getAll(); for (User user : all) { System.out.println(user); } sqlSession.commit(); } } @Test public void updateUser () { try (SqlSession sqlSession = MybatisUtils.getSqlSession()){ UserMapper mapper = sqlSession.getMapper(UserMapper.class ) ; User user = mapper.getById(1 ); user.setName("Cobain" ); int i = mapper.updateUser(user); if (i>0 ){ System.out.println("修改成功" ); } List<User> all = mapper.getAll(); for (User user1 : all) { System.out.println(user1); } sqlSession.commit(); } } @Test public void deleteUser () { try (SqlSession sqlSession = MybatisUtils.getSqlSession()){ UserMapper mapper = sqlSession.getMapper(UserMapper.class ) ; int i = mapper.deleteUser(0 ); if (i>0 ){ System.out.println("删除成功" ); } List<User> all = mapper.getAll(); for (User user : all) { System.out.println(user); } sqlSession.commit(); } } }
万能的Map 使用实体类进行传参,在sql中是取出它的字段名;二map是取出它的key;
map可以进行数据塑形,根据你需要的来插入、更新,一般在局部更新和多参数中比较有用。
1 int addUserMap (Map<String, Object> map) ;
1 2 3 <insert id ="addUserMap" > insert into user (id, name, pwd) values (#{a}, #{b}, #{c}); </insert >
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 @Test public void addUserMap () { try (SqlSession sqlSession = MybatisUtils.getSqlSession()){ UserMapper mapper = sqlSession.getMapper(UserMapper.class ) ; Map<String, Object> map = new HashMap<>(); map.put("a" , 7 ); map.put("b" , "ChenZheKai" ); map.put("c" , "123456" ); int i = mapper.addUserMap(map); if (i>0 ){ System.out.println("插入成功" ); } sqlSession.commit(); } }
模糊查询 1 List<User> getUserLike (String name) ;
1 2 3 <select id ="getUserLike" resultType ="com.muchlab.entity.User" > select * from user alias where alias.name like "%"#{name}"%"; </select >
1 2 3 4 5 6 7 8 9 10 @Test public void addUserLike () { try (SqlSession sqlSession = MybatisUtils.getSqlSession()){ UserMapper mapper = sqlSession.getMapper(UserMapper.class ) ; List<User> userLike = mapper.getUserLike("b" ); for (User user : userLike) { System.out.println(user); } } }
参考资料:B站狂神