day69
mybatis
开发步骤
查询
前期准备:数据库表结构和表数据准备
mysql> select * from user; +-----+----------+----------+-------+-------+---------+ | uid | username | password | email | phone | address | +-----+----------+----------+-------+-------+---------+ | 1 | admin | 123456 | NULL | NULL | sushe | | 2 | user | 123456 | NULL | NULL | sushe | | 3 | zhangsan | 654321 | NULL | NULL | sushe | | 4 | lisi | 654321 | NULL | NULL | sushe | | 5 | wangwu | 654321 | NULL | NULL | sushe | | 6 | zhaoliu | 654321 | NULL | NULL | sushe | | 7 | sunqi | 654321 | NULL | NULL | sushe | | 8 | zhouba | 654321 | NULL | NULL | sushe | | 9 | zhoubapi | 654321 | NULL | NULL | sushe | +-----+----------+----------+-------+-------+---------+ 9 rows in set (0.00 sec)配置pom.xml依赖文件
<dependencies><dependency><groupId>junit</groupId><artifactId>junit</artifactId><version>4.12</version><scope>test</scope></dependency> <dependency><groupId>org.mybatis</groupId><artifactId>mybatis</artifactId><version>3.4.6</version></dependency> <dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><version>5.1.46</version></dependency> <dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId><version>1.18.16</version><scope>provided</scope></dependency> </dependencies>新增pojo类
package com.saas.pojo; import lombok.Data; @Data public class User { private int uid ;private String username;private String password;private String email ;private String phone ;private String address ; }新增测试类
package com.saas.dao; import com.saas.pojo.User; 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 org.junit.Test; import java.io.IOException; import java.io.InputStream; import java.util.List; public class TestUserDao { @Testpublic void testGetAllUsers(){String conf = "mybatis-config.xml"; try {InputStream is = Resources.getResourceAsStream(conf); SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(is); SqlSession session = factory.openSession(); List<User> list = session.selectList("com.saas.dao.UserMapper.getAllUsers"); for (User u : list) {System.out.println(u);} session.close();} catch (IOException e) {throw new RuntimeException(e);}} }mybatis-config.xml
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE configurationPUBLIC "-//mybatis.org//DTD Config 3.0//EN""https://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.jdbc.Driver"/><property name="url" value="jdbc:mysql://localhost:3306/saas?useSSL=false"/><property name="username" value="root"/><property name="password" value="Abc@1234"/></dataSource></environment></environments><mappers><mapper resource="com/saas/dao/UserMapper.xml"/></mappers> </configuration>UserMapper.xml
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE mapperPUBLIC "-//mybatis.org//DTD Mapper 3.0//EN""https://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="com.saas.dao.UserMapper"><select id="getAllUsers" resultType="com.saas.pojo.User">select * from user</select> </mapper>展示运行结果
User(uid=1, username=admin, password=123456, email=null, phone=null, address=sushe) User(uid=2, username=user, password=123456, email=null, phone=null, address=sushe) User(uid=3, username=zhangsan, password=654321, email=null, phone=null, address=sushe) User(uid=4, username=lisi, password=654321, email=null, phone=null, address=sushe) User(uid=5, username=wangwu, password=654321, email=null, phone=null, address=sushe) User(uid=6, username=zhaoliu, password=654321, email=null, phone=null, address=sushe) User(uid=7, username=sunqi, password=654321, email=null, phone=null, address=sushe) User(uid=8, username=zhouba, password=654321, email=null, phone=null, address=sushe) User(uid=9, username=zhoubapi, password=654321, email=null, phone=null, address=sushe)以上得到最后的查询结果
注意:
使用mybatis,其核心是SqlSession对象
SqlSession对象使用SqlSessionFactory获取
SqlSessionFactory通过SqlSessionFactoryBuilder获取
SqlSessionFactoryBuilder需要读取mybatis的核心配置文件
从mybaits3开始,官方建议使用namespace,最终在进行crud功能时所需要的statement是namespace+id
所以要求在整个项目中,namespace+id必须唯一
活用JUnit的生命周期
package com.saas.dao; import org.junit.*; public class TestJUnit { @BeforeClasspublic static void beforeClass(){System.out.println("this is beforeClass");} @AfterClasspublic static void afterClass(){System.out.println("this is afterClass");} @Beforepublic void setup(){System.out.println("this is setup");} @Afterpublic void tearDown(){System.out.println("this is tearDown");} @Testpublic void test01(){System.out.println("this is test01");}@Testpublic void test02(){System.out.println("this is test02");}@Testpublic void test03(){System.out.println("this is test03");} }执行结果:
this is beforeClass this is setup this is test01 this is tearDown this is setup this is test02 this is tearDown this is setup this is test03 this is tearDown this is afterClass通过以上的运行结果发现
这个@BeforeClass注解对应的方法,不管有几个测试方法,都在开头只执行一次
这个@AfterClass注解对应的方法,不管有几个测试方法,都在最后只执行一次
这个@Before注解对应的方法,有几个测试方法,在每个测试方法之前都执行一次
这个@After注解对应的方法,有几个测试方法,在每个测试方法之后都执行一次
package com.saas.dao;import com.saas.pojo.User; 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 org.junit.After; import org.junit.Before; import org.junit.Test;import java.io.IOException; import java.io.InputStream; import java.util.HashMap; import java.util.List; import java.util.Map;public class TestUserDao02 {SqlSession session;@Beforepublic void setup(){String conf = "mybatis-config.xml";try {InputStream is = Resources.getResourceAsStream(conf);SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(is);session = factory.openSession();}catch (IOException e) {throw new RuntimeException(e);}}@Afterpublic void tearDown(){if (session != null){session.close();session = null;}}@Testpublic void testGetAllUsers(){List<User> list = session.selectList("com.saas.dao.UserMapper.getAllUsers");for (User u : list) {System.out.println(u);}}@Testpublic void testGetUserByUid(){User user = session.selectOne("com.saas.dao.UserMapper.getUserByUid", 9);System.out.println(user);}@Testpublic void testGetUsersByPage(){Map<String, Integer> map = new HashMap<>();map.put("start", 6);map.put("size", 3);List<User> list = session.selectList("com.saas.dao.UserMapper.getUsersByPage", map);for (User u : list) {System.out.println(u);}} }<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE mapperPUBLIC "-//mybatis.org//DTD Mapper 3.0//EN""https://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="com.saas.dao.UserMapper"><select id="getAllUsers" resultType="com.saas.pojo.User">select * from user</select><select id="getUserByUid" resultType="com.saas.pojo.User">select * from user where uid = #{abc}</select><select id="getUsersByPage" resultType="com.saas.pojo.User">select * from user limit #{start},#{size}</select> </mapper>在整个项目中所有的namespace+id应该唯一
增删改操作
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE mapperPUBLIC "-//mybatis.org//DTD Mapper 3.0//EN""https://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="com.saas.dao.UserMapper"><select id="getAllUsers" resultType="com.saas.pojo.User">select * from user</select><select id="getUserByUid" resultType="com.saas.pojo.User">select * from user where uid = #{abc}</select><select id="getUsersByPage" resultType="com.saas.pojo.User">select * from user limit #{start},#{size}</select><insert id="saveUser">insert into user(username,password,email,phone,address) values(#{username},#{password},#{email},#{phone},#{address})</insert><update id="updateUser">update user set username=#{username},password=#{password},email=#{email},phone=#{phone},address=#{address} where uid=#{uid}</update> </mapper>package com.saas.dao;import com.saas.pojo.User; 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 org.junit.After; import org.junit.Before; import org.junit.Test;import java.io.IOException; import java.io.InputStream; import java.util.HashMap; import java.util.List; import java.util.Map;public class TestUserDao02 {SqlSession session;@Beforepublic void setup(){String conf = "mybatis-config.xml";try {InputStream is = Resources.getResourceAsStream(conf);SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(is);session = factory.openSession();}catch (IOException e) {throw new RuntimeException(e);}}@Afterpublic void tearDown(){if (session != null){session.close();session = null;}}@Testpublic void testGetAllUsers(){List<User> list = session.selectList("com.saas.dao.UserMapper.getAllUsers");for (User u : list) {System.out.println(u);}}@Testpublic void testGetUserByUid(){User user = session.selectOne("com.saas.dao.UserMapper.getUserByUid", 9);System.out.println(user);}@Testpublic void testGetUsersByPage(){Map<String, Integer> map = new HashMap<>();map.put("start", 6);map.put("size", 3);List<User> list = session.selectList("com.saas.dao.UserMapper.getUsersByPage", map);for (User u : list) {System.out.println(u);}}@Testpublic void testSaveUser(){User user = new User();user.setUsername("test");user.setPassword("123456");user.setEmail("test@163.com");user.setPhone("123456789");user.setAddress("test");int result = session.insert("com.saas.dao.UserMapper.saveUser", user);System.out.println(result > 0);}@Testpublic void testUpdateUser(){User user = new User();user.setUid(9);user.setUsername("test09");user.setPassword("123456");user.setEmail("test@163.com");user.setPhone("123456789");user.setAddress("test");int result = session.update("com.saas.dao.UserMapper.updateUser", user);System.out.println(result > 0);session.commit();} }注意:
mybatis默认事务是开启状态,进行任何的增删改操作结束后,事务默认是不提交的。
所以有两种方式解决:
在SqlSessionFactory对象的openSession方法中传递一个autocommit为true的值,让每次增删改之后,默认自动提交
openSession方法不传递参数,默认为false,是不自动提交,可以在做完增删改之后,进行手动提交,SqlSession对象的commit方法,完成手动提交功能