文章轉載:http://www.cnblogs.com/xdp-gacl/category/655890.html
上一篇博文MyBatis學習總結(一)——MyBatis快速入門中我們講了如何使用Mybatis查詢users表中的資料,算是對MyBatis有一個初步的入門了,今天講解一下如何使用MyBatis對users表執行CRUD操作。本文中使用到的測試環境是上一篇博文中的測試環境。
一、使用MyBatis對表執行CRUD操作——基于XML的實作
1、定義sql映射xml檔案
userMapper.xml檔案的内容如下:
![](https://img.laitimes.com/img/9ZDMuAjOiMmIsIjOiQnIsIiZpdmLlR2bjlHcvN2LcNXZnFWbp9CXt92YuM3ZvxmYuNmLu9Wbt92Yvw1LcpDc0RHaiojIsJye.gif)
1 <?xml version="1.0" encoding="UTF-8" ?>
2 <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
3 <!-- 為這個mapper指定一個唯一的namespace,namespace的值習慣上設定成包名+sql映射檔案名,這樣就能夠保證namespace的值是唯一的
4 例如namespace="me.gacl.mapping.userMapper"就是me.gacl.mapping(包名)+userMapper(userMapper.xml檔案去除字尾)
5 -->
6 <mapper namespace="me.gacl.mapping.userMapper">
7 <!-- 在select标簽中編寫查詢的SQL語句, 設定select标簽的id屬性為getUser,id屬性值必須是唯一的,不能夠重複
8 使用parameterType屬性指明查詢時使用的參數類型,resultType屬性指明查詢傳回的結果集類型
9 resultType="me.gacl.domain.User"就表示将查詢結果封裝成一個User類的對象傳回
10 User類就是users表所對應的實體類
11 -->
12 <!--
13 根據id查詢得到一個user對象
14 -->
15 <select id="getUser" parameterType="int"
16 resultType="me.gacl.domain.User">
17 select * from users where id=#{id}
18 </select>
19
20 <!-- 建立使用者(Create) -->
21 <insert id="addUser" parameterType="me.gacl.domain.User">
22 insert into users(name,age) values(#{name},#{age})
23 </insert>
24
25 <!-- 删除使用者(Remove) -->
26 <delete id="deleteUser" parameterType="int">
27 delete from users where id=#{id}
28 </delete>
29
30 <!-- 修改使用者(Update) -->
31 <update id="updateUser" parameterType="me.gacl.domain.User">
32 update users set name=#{name},age=#{age} where id=#{id}
33 </update>
34
35 <!-- 查詢全部使用者-->
36 <select id="getAllUsers" resultType="me.gacl.domain.User">
37 select * from users
38 </select>
39
40 </mapper>
![](https://img.laitimes.com/img/9ZDMuAjOiMmIsIjOiQnIsIiZpdmLlR2bjlHcvN2LcNXZnFWbp9CXt92YuM3ZvxmYuNmLu9Wbt92Yvw1LcpDc0RHaiojIsJye.gif)
單元測試類代碼如下:
![](https://img.laitimes.com/img/9ZDMuAjOiMmIsIjOiQnIsIiZpdmLlR2bjlHcvN2LcNXZnFWbp9CXt92YuM3ZvxmYuNmLu9Wbt92Yvw1LcpDc0RHaiojIsJye.gif)
1 package me.gacl.test;
2
3 import java.util.List;
4 import me.gacl.domain.User;
5 import me.gacl.util.MyBatisUtil;
6 import org.apache.ibatis.session.SqlSession;
7 import org.junit.Test;
8
9 public class TestCRUDByXmlMapper {
10
11 @Test
12 public void testAdd(){
13 //SqlSession sqlSession = MyBatisUtil.getSqlSession(false);
14 SqlSession sqlSession = MyBatisUtil.getSqlSession(true);
15 /**
16 * 映射sql的辨別字元串,
17 * me.gacl.mapping.userMapper是userMapper.xml檔案中mapper标簽的namespace屬性的值,
18 * addUser是insert标簽的id屬性值,通過insert标簽的id屬性值就可以找到要執行的SQL
19 */
20 String statement = "me.gacl.mapping.userMapper.addUser";//映射sql的辨別字元串
21 User user = new User();
22 user.setName("使用者孤傲蒼狼");
23 user.setAge(20);
24 //執行插入操作
25 int retResult = sqlSession.insert(statement,user);
26 //手動送出事務
27 //sqlSession.commit();
28 //使用SqlSession執行完SQL之後需要關閉SqlSession
29 sqlSession.close();
30 System.out.println(retResult);
31 }
32
33 @Test
34 public void testUpdate(){
35 SqlSession sqlSession = MyBatisUtil.getSqlSession(true);
36 /**
37 * 映射sql的辨別字元串,
38 * me.gacl.mapping.userMapper是userMapper.xml檔案中mapper标簽的namespace屬性的值,
39 * updateUser是update标簽的id屬性值,通過update标簽的id屬性值就可以找到要執行的SQL
40 */
41 String statement = "me.gacl.mapping.userMapper.updateUser";//映射sql的辨別字元串
42 User user = new User();
43 user.setId(3);
44 user.setName("孤傲蒼狼");
45 user.setAge(25);
46 //執行修改操作
47 int retResult = sqlSession.update(statement,user);
48 //使用SqlSession執行完SQL之後需要關閉SqlSession
49 sqlSession.close();
50 System.out.println(retResult);
51 }
52
53 @Test
54 public void testDelete(){
55 SqlSession sqlSession = MyBatisUtil.getSqlSession(true);
56 /**
57 * 映射sql的辨別字元串,
58 * me.gacl.mapping.userMapper是userMapper.xml檔案中mapper标簽的namespace屬性的值,
59 * deleteUser是delete标簽的id屬性值,通過delete标簽的id屬性值就可以找到要執行的SQL
60 */
61 String statement = "me.gacl.mapping.userMapper.deleteUser";//映射sql的辨別字元串
62 //執行删除操作
63 int retResult = sqlSession.delete(statement,5);
64 //使用SqlSession執行完SQL之後需要關閉SqlSession
65 sqlSession.close();
66 System.out.println(retResult);
67 }
68
69 @Test
70 public void testGetAll(){
71 SqlSession sqlSession = MyBatisUtil.getSqlSession();
72 /**
73 * 映射sql的辨別字元串,
74 * me.gacl.mapping.userMapper是userMapper.xml檔案中mapper标簽的namespace屬性的值,
75 * getAllUsers是select标簽的id屬性值,通過select标簽的id屬性值就可以找到要執行的SQL
76 */
77 String statement = "me.gacl.mapping.userMapper.getAllUsers";//映射sql的辨別字元串
78 //執行查詢操作,将查詢結果自動封裝成List<User>傳回
79 List<User> lstUsers = sqlSession.selectList(statement);
80 //使用SqlSession執行完SQL之後需要關閉SqlSession
81 sqlSession.close();
82 System.out.println(lstUsers);
83 }
84 }
![](https://img.laitimes.com/img/9ZDMuAjOiMmIsIjOiQnIsIiZpdmLlR2bjlHcvN2LcNXZnFWbp9CXt92YuM3ZvxmYuNmLu9Wbt92Yvw1LcpDc0RHaiojIsJye.gif)
二、使用MyBatis對表執行CRUD操作——基于注解的實作
1、定義sql映射的接口
UserMapperI接口的代碼如下:
![](https://img.laitimes.com/img/9ZDMuAjOiMmIsIjOiQnIsIiZpdmLlR2bjlHcvN2LcNXZnFWbp9CXt92YuM3ZvxmYuNmLu9Wbt92Yvw1LcpDc0RHaiojIsJye.gif)
1 package me.gacl.mapping;
2
3 import java.util.List;
4 import me.gacl.domain.User;
5 import org.apache.ibatis.annotations.Delete;
6 import org.apache.ibatis.annotations.Insert;
7 import org.apache.ibatis.annotations.Select;
8 import org.apache.ibatis.annotations.Update;
9
10 /**
11 * @author gacl
12 * 定義sql映射的接口,使用注解指明方法要執行的SQL
13 */
14 public interface UserMapperI {
15
16 //使用@Insert注解指明add方法要執行的SQL
17 @Insert("insert into users(name, age) values(#{name}, #{age})")
18 public int add(User user);
19
20 //使用@Delete注解指明deleteById方法要執行的SQL
21 @Delete("delete from users where id=#{id}")
22 public int deleteById(int id);
23
24 //使用@Update注解指明update方法要執行的SQL
25 @Update("update users set name=#{name},age=#{age} where id=#{id}")
26 public int update(User user);
27
28 //使用@Select注解指明getById方法要執行的SQL
29 @Select("select * from users where id=#{id}")
30 public User getById(int id);
31
32 //使用@Select注解指明getAll方法要執行的SQL
33 @Select("select * from users")
34 public List<User> getAll();
35 }
![](https://img.laitimes.com/img/9ZDMuAjOiMmIsIjOiQnIsIiZpdmLlR2bjlHcvN2LcNXZnFWbp9CXt92YuM3ZvxmYuNmLu9Wbt92Yvw1LcpDc0RHaiojIsJye.gif)
需要說明的是,我們不需要針對UserMapperI接口去編寫具體的實作類代碼,這個具體的實作類由MyBatis幫我們動态建構出來,我們隻需要直接拿來使用即可。
2、在conf.xml檔案中注冊這個映射接口
![](https://img.laitimes.com/img/9ZDMuAjOiMmIsIjOiQnIsIiZpdmLlR2bjlHcvN2LcNXZnFWbp9CXt92YuM3ZvxmYuNmLu9Wbt92Yvw1LcpDc0RHaiojIsJye.gif)
1 <?xml version="1.0" encoding="UTF-8"?>
2 <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd">
3 <configuration>
4 <environments default="development">
5 <environment id="development">
6 <transactionManager type="JDBC" />
7 <!-- 配置資料庫連接配接資訊 -->
8 <dataSource type="POOLED">
9 <property name="driver" value="com.mysql.jdbc.Driver" />
10 <property name="url" value="jdbc:mysql://localhost:3306/mybatis" />
11 <property name="username" value="root" />
12 <property name="password" value="XDP" />
13 </dataSource>
14 </environment>
15 </environments>
16
17 <mappers>
18 <!-- 注冊userMapper.xml檔案,
19 userMapper.xml位于me.gacl.mapping這個包下,是以resource寫成me/gacl/mapping/userMapper.xml-->
20 <mapper resource="me/gacl/mapping/userMapper.xml"/>
21 <!-- 注冊UserMapper映射接口-->
22 <mapper class="me.gacl.mapping.UserMapperI"/>
23 </mappers>
24
25 </configuration>
![](https://img.laitimes.com/img/9ZDMuAjOiMmIsIjOiQnIsIiZpdmLlR2bjlHcvN2LcNXZnFWbp9CXt92YuM3ZvxmYuNmLu9Wbt92Yvw1LcpDc0RHaiojIsJye.gif)
單元測試類的代碼如下:
![](https://img.laitimes.com/img/9ZDMuAjOiMmIsIjOiQnIsIiZpdmLlR2bjlHcvN2LcNXZnFWbp9CXt92YuM3ZvxmYuNmLu9Wbt92Yvw1LcpDc0RHaiojIsJye.gif)
1 package me.gacl.test;
2
3 import java.util.List;
4 import me.gacl.domain.User;
5 import me.gacl.mapping.UserMapperI;
6 import me.gacl.util.MyBatisUtil;
7 import org.apache.ibatis.session.SqlSession;
8 import org.junit.Test;
9
10 public class TestCRUDByAnnotationMapper {
11
12 @Test
13 public void testAdd(){
14 SqlSession sqlSession = MyBatisUtil.getSqlSession(true);
15 //得到UserMapperI接口的實作類對象,UserMapperI接口的實作類對象由sqlSession.getMapper(UserMapperI.class)動态建構出來
16 UserMapperI mapper = sqlSession.getMapper(UserMapperI.class);
17 User user = new User();
18 user.setName("使用者xdp");
19 user.setAge(20);
20 int add = mapper.add(user);
21 //使用SqlSession執行完SQL之後需要關閉SqlSession
22 sqlSession.close();
23 System.out.println(add);
24 }
25
26 @Test
27 public void testUpdate(){
28 SqlSession sqlSession = MyBatisUtil.getSqlSession(true);
29 //得到UserMapperI接口的實作類對象,UserMapperI接口的實作類對象由sqlSession.getMapper(UserMapperI.class)動态建構出來
30 UserMapperI mapper = sqlSession.getMapper(UserMapperI.class);
31 User user = new User();
32 user.setId(3);
33 user.setName("孤傲蒼狼_xdp");
34 user.setAge(26);
35 //執行修改操作
36 int retResult = mapper.update(user);
37 //使用SqlSession執行完SQL之後需要關閉SqlSession
38 sqlSession.close();
39 System.out.println(retResult);
40 }
41
42 @Test
43 public void testDelete(){
44 SqlSession sqlSession = MyBatisUtil.getSqlSession(true);
45 //得到UserMapperI接口的實作類對象,UserMapperI接口的實作類對象由sqlSession.getMapper(UserMapperI.class)動态建構出來
46 UserMapperI mapper = sqlSession.getMapper(UserMapperI.class);
47 //執行删除操作
48 int retResult = mapper.deleteById(7);
49 //使用SqlSession執行完SQL之後需要關閉SqlSession
50 sqlSession.close();
51 System.out.println(retResult);
52 }
53
54 @Test
55 public void testGetUser(){
56 SqlSession sqlSession = MyBatisUtil.getSqlSession();
57 //得到UserMapperI接口的實作類對象,UserMapperI接口的實作類對象由sqlSession.getMapper(UserMapperI.class)動态建構出來
58 UserMapperI mapper = sqlSession.getMapper(UserMapperI.class);
59 //執行查詢操作,将查詢結果自動封裝成User傳回
60 User user = mapper.getById(8);
61 //使用SqlSession執行完SQL之後需要關閉SqlSession
62 sqlSession.close();
63 System.out.println(user);
64 }
65
66 @Test
67 public void testGetAll(){
68 SqlSession sqlSession = MyBatisUtil.getSqlSession();
69 //得到UserMapperI接口的實作類對象,UserMapperI接口的實作類對象由sqlSession.getMapper(UserMapperI.class)動态建構出來
70 UserMapperI mapper = sqlSession.getMapper(UserMapperI.class);
71 //執行查詢操作,将查詢結果自動封裝成List<User>傳回
72 List<User> lstUsers = mapper.getAll();
73 //使用SqlSession執行完SQL之後需要關閉SqlSession
74 sqlSession.close();
75 System.out.println(lstUsers);
76 }
77 }
![](https://img.laitimes.com/img/9ZDMuAjOiMmIsIjOiQnIsIiZpdmLlR2bjlHcvN2LcNXZnFWbp9CXt92YuM3ZvxmYuNmLu9Wbt92Yvw1LcpDc0RHaiojIsJye.gif)
用到的MyBatisUtil工具類代碼如下:
![](https://img.laitimes.com/img/9ZDMuAjOiMmIsIjOiQnIsIiZpdmLlR2bjlHcvN2LcNXZnFWbp9CXt92YuM3ZvxmYuNmLu9Wbt92Yvw1LcpDc0RHaiojIsJye.gif)
1 package me.gacl.util;
2
3 import java.io.InputStream;
4
5 import org.apache.ibatis.session.SqlSession;
6 import org.apache.ibatis.session.SqlSessionFactory;
7 import org.apache.ibatis.session.SqlSessionFactoryBuilder;
8
9 public class MyBatisUtil {
10
11 /**
12 * 擷取SqlSessionFactory
13 * @return SqlSessionFactory
14 */
15 public static SqlSessionFactory getSqlSessionFactory() {
16 String resource = "conf.xml";
17 InputStream is = MyBatisUtil.class.getClassLoader().getResourceAsStream(resource);
18 SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(is);
19 return factory;
20 }
21
22 /**
23 * 擷取SqlSession
24 * @return SqlSession
25 */
26 public static SqlSession getSqlSession() {
27 return getSqlSessionFactory().openSession();
28 }
29
30 /**
31 * 擷取SqlSession
32 * @param isAutoCommit
33 * true 表示建立的SqlSession對象在執行完SQL之後會自動送出事務
34 * false 表示建立的SqlSession對象在執行完SQL之後不會自動送出事務,這時就需要我們手動調用sqlSession.commit()送出事務
35 * @return SqlSession
36 */
37 public static SqlSession getSqlSession(boolean isAutoCommit) {
38 return getSqlSessionFactory().openSession(isAutoCommit);
39 }
40 }
![](https://img.laitimes.com/img/9ZDMuAjOiMmIsIjOiQnIsIiZpdmLlR2bjlHcvN2LcNXZnFWbp9CXt92YuM3ZvxmYuNmLu9Wbt92Yvw1LcpDc0RHaiojIsJye.gif)
以上的相關代碼是全部測試通過的,關于使用MyBatis對表執行CRUD操作的内容就這麼多。