上一篇文章MyBatis入門學習教程(一)-MyBatis快速入門中我們講了如何使用Mybatis查詢users表中的數據,算是對MyBatis有一個初步的入門了,今天講解一下如何使用MyBatis對users表執行CRUD操作。在沒奔主題之前,先給大家補充點有關mybatis和crud的基本知識。
什么是 MyBatis?
MyBatis 是支持普通 SQL 查詢,存儲過程和高級映射的優秀持久層框架。 MyBatis 消除了幾乎所有的 JDBC 代碼和參數的手工設置以及對結果集的檢索。MyBatis 可以使用簡單的XML 或注解用于配置和原始映射,將接口和 Java 的 POJO(Plain Old Java Objects,普通的Java對象)映射成數據庫中的記錄。
MyBatis下載:https://github.com/mybatis/mybatis-3/releases
crud的意思
CRUD是指在做計算處理時的增加(Create)、重新取得數據(Retrieve)、更新(Update)和刪除(Delete)幾個單詞的首字母簡寫。主要被用在描述軟件系統中數據庫或者持久層的基本操作功能。
步入正題,本文中使用到的測試環境是上一篇文中的測試環境。
一、使用MyBatis對表執行CRUD操作——基于XML的實現
1、定義sql映射xml文件
userMapper.xml文件的內容如下:
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
|
<?xml version= "." encoding= "UTF-" ?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper .//EN" "http://mybatis.org/dtd/mybatis--mapper.dtd" > <!-- 為這個mapper指定一個唯一的namespace,namespace的值習慣上設置成包名+sql映射文件名,這樣就能夠保證namespace的值是唯一的 例如namespace= "me.gacl.mapping.userMapper" 就是me.gacl.mapping(包名)+userMapper(userMapper.xml文件去除后綴) --> <mapper namespace= "me.gacl.mapping.userMapper" > <!-- 在select標簽中編寫查詢的SQL語句, 設置select標簽的id屬性為getUser,id屬性值必須是唯一的,不能夠重復 使用parameterType屬性指明查詢時使用的參數類型,resultType屬性指明查詢返回的結果集類型 resultType= "me.gacl.domain.User" 就表示將查詢結果封裝成一個User類的對象返回 User類就是users表所對應的實體類 --> <!-- 根據id查詢得到一個user對象 --> <select id= "getUser" parameterType= "int" resultType= "me.gacl.domain.User" > select * from users where id=#{id} </select> <!-- 創建用戶(Create) --> <insert id= "addUser" parameterType= "me.gacl.domain.User" > insert into users(name,age) values(#{name},#{age}) </insert> <!-- 刪除用戶(Remove) --> <delete id= "deleteUser" parameterType= "int" > delete from users where id=#{id} </delete> <!-- 修改用戶(Update) --> <update id= "updateUser" parameterType= "me.gacl.domain.User" > update users set name=#{name},age=#{age} where id=#{id} </update> <!-- 查詢全部用戶--> <select id= "getAllUsers" resultType= "me.gacl.domain.User" > select * from users </select> </mapper> |
單元測試類代碼如下:
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
|
package me.gacl.test; import java.util.List; import me.gacl.domain.User; import me.gacl.util.MyBatisUtil; import org.apache.ibatis.session.SqlSession; import org.junit.Test; public class TestCRUDByXmlMapper { @Test public void testAdd(){ //SqlSession sqlSession = MyBatisUtil.getSqlSession(false); SqlSession sqlSession = MyBatisUtil.getSqlSession( true ); /** * 映射sql的標識字符串, * me.gacl.mapping.userMapper是userMapper.xml文件中mapper標簽的namespace屬性的值, * addUser是insert標簽的id屬性值,通過insert標簽的id屬性值就可以找到要執行的SQL */ String statement = "me.gacl.mapping.userMapper.addUser" ; //映射sql的標識字符串 User user = new User(); user.setName( "用戶孤傲蒼狼" ); user.setAge(); //執行插入操作 int retResult = sqlSession.insert(statement,user); //手動提交事務 //sqlSession.commit(); //使用SqlSession執行完SQL之后需要關閉SqlSession sqlSession.close(); System.out.println(retResult); } @Test public void testUpdate(){ SqlSession sqlSession = MyBatisUtil.getSqlSession( true ); /** * 映射sql的標識字符串, * me.gacl.mapping.userMapper是userMapper.xml文件中mapper標簽的namespace屬性的值, * updateUser是update標簽的id屬性值,通過update標簽的id屬性值就可以找到要執行的SQL */ String statement = "me.gacl.mapping.userMapper.updateUser" ; //映射sql的標識字符串 User user = new User(); user.setId(); user.setName( "孤傲蒼狼" ); user.setAge(); //執行修改操作 int retResult = sqlSession.update(statement,user); //使用SqlSession執行完SQL之后需要關閉SqlSession sqlSession.close(); System.out.println(retResult); } @Test public void testDelete(){ SqlSession sqlSession = MyBatisUtil.getSqlSession( true ); /** * 映射sql的標識字符串, * me.gacl.mapping.userMapper是userMapper.xml文件中mapper標簽的namespace屬性的值, * deleteUser是delete標簽的id屬性值,通過delete標簽的id屬性值就可以找到要執行的SQL */ String statement = "me.gacl.mapping.userMapper.deleteUser" ; //映射sql的標識字符串 //執行刪除操作 int retResult = sqlSession.delete(statement,); //使用SqlSession執行完SQL之后需要關閉SqlSession sqlSession.close(); System.out.println(retResult); } @Test public void testGetAll(){ SqlSession sqlSession = MyBatisUtil.getSqlSession(); /** * 映射sql的標識字符串, * me.gacl.mapping.userMapper是userMapper.xml文件中mapper標簽的namespace屬性的值, * getAllUsers是select標簽的id屬性值,通過select標簽的id屬性值就可以找到要執行的SQL */ String statement = "me.gacl.mapping.userMapper.getAllUsers" ; //映射sql的標識字符串 //執行查詢操作,將查詢結果自動封裝成List<User>返回 List<User> lstUsers = sqlSession.selectList(statement); //使用SqlSession執行完SQL之后需要關閉SqlSession sqlSession.close(); System.out.println(lstUsers); } } |
二、使用MyBatis對表執行CRUD操作——基于注解的實現
1、定義sql映射的接口
UserMapperI接口的代碼如下:
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
|
package me.gacl.mapping; import java.util.List; import me.gacl.domain.User; import org.apache.ibatis.annotations.Delete; import org.apache.ibatis.annotations.Insert; import org.apache.ibatis.annotations.Select; import org.apache.ibatis.annotations.Update; /** * @author gacl * 定義sql映射的接口,使用注解指明方法要執行的SQL */ public interface UserMapperI { //使用@Insert注解指明add方法要執行的SQL @Insert ( "insert into users(name, age) values(#{name}, #{age})" ) public int add(User user); //使用@Delete注解指明deleteById方法要執行的SQL @Delete ( "delete from users where id=#{id}" ) public int deleteById( int id); //使用@Update注解指明update方法要執行的SQL @Update ( "update users set name=#{name},age=#{age} where id=#{id}" ) public int update(User user); //使用@Select注解指明getById方法要執行的SQL @Select ( "select * from users where id=#{id}" ) public User getById( int id); //使用@Select注解指明getAll方法要執行的SQL @Select ( "select * from users" ) public List<User> getAll(); } |
需要說明的是,我們不需要針對UserMapperI接口去編寫具體的實現類代碼,這個具體的實現類由MyBatis幫我們動態構建出來,我們只需要直接拿來使用即可。
2、在conf.xml文件中注冊這個映射接口
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= "." encoding= "UTF-" ?> <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config .//EN" "http://mybatis.org/dtd/mybatis--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:/mybatis" /> <property name= "username" value= "root" /> <property name= "password" value= "XDP" /> </dataSource> </environment> </environments> <mappers> <!-- 注冊userMapper.xml文件, userMapper.xml位于me.gacl.mapping這個包下,所以resource寫成me/gacl/mapping/userMapper.xml--> <mapper resource= "me/gacl/mapping/userMapper.xml" /> <!-- 注冊UserMapper映射接口--> <mapper class = "me.gacl.mapping.UserMapperI" /> </mappers> </configuration> |
單元測試類的代碼如下:
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
|
package me.gacl.test; import java.util.List; import me.gacl.domain.User; import me.gacl.mapping.UserMapperI; import me.gacl.util.MyBatisUtil; import org.apache.ibatis.session.SqlSession; import org.junit.Test; public class TestCRUDByAnnotationMapper { @Test public void testAdd(){ SqlSession sqlSession = MyBatisUtil.getSqlSession( true ); //得到UserMapperI接口的實現類對象,UserMapperI接口的實現類對象由sqlSession.getMapper(UserMapperI.class)動態構建出來 UserMapperI mapper = sqlSession.getMapper(UserMapperI. class ); User user = new User(); user.setName( "用戶xdp" ); user.setAge(); int add = mapper.add(user); //使用SqlSession執行完SQL之后需要關閉SqlSession sqlSession.close(); System.out.println(add); } @Test public void testUpdate(){ SqlSession sqlSession = MyBatisUtil.getSqlSession( true ); //得到UserMapperI接口的實現類對象,UserMapperI接口的實現類對象由sqlSession.getMapper(UserMapperI.class)動態構建出來 UserMapperI mapper = sqlSession.getMapper(UserMapperI. class ); User user = new User(); user.setId(); user.setName( "孤傲蒼狼_xdp" ); user.setAge(); //執行修改操作 int retResult = mapper.update(user); //使用SqlSession執行完SQL之后需要關閉SqlSession sqlSession.close(); System.out.println(retResult); } @Test public void testDelete(){ SqlSession sqlSession = MyBatisUtil.getSqlSession( true ); //得到UserMapperI接口的實現類對象,UserMapperI接口的實現類對象由sqlSession.getMapper(UserMapperI.class)動態構建出來 UserMapperI mapper = sqlSession.getMapper(UserMapperI. class ); //執行刪除操作 int retResult = mapper.deleteById(); //使用SqlSession執行完SQL之后需要關閉SqlSession sqlSession.close(); System.out.println(retResult); } @Test public void testGetUser(){ SqlSession sqlSession = MyBatisUtil.getSqlSession(); //得到UserMapperI接口的實現類對象,UserMapperI接口的實現類對象由sqlSession.getMapper(UserMapperI.class)動態構建出來 UserMapperI mapper = sqlSession.getMapper(UserMapperI. class ); //執行查詢操作,將查詢結果自動封裝成User返回 User user = mapper.getById(); //使用SqlSession執行完SQL之后需要關閉SqlSession sqlSession.close(); System.out.println(user); } @Test public void testGetAll(){ SqlSession sqlSession = MyBatisUtil.getSqlSession(); //得到UserMapperI接口的實現類對象,UserMapperI接口的實現類對象由sqlSession.getMapper(UserMapperI.class)動態構建出來 UserMapperI mapper = sqlSession.getMapper(UserMapperI. class ); //執行查詢操作,將查詢結果自動封裝成List<User>返回 List<User> lstUsers = mapper.getAll(); //使用SqlSession執行完SQL之后需要關閉SqlSession sqlSession.close(); System.out.println(lstUsers); } } |
用到的MyBatisUtil工具類代碼如下:
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
|
package me.gacl.util; import java.io.InputStream; import org.apache.ibatis.session.SqlSession; import org.apache.ibatis.session.SqlSessionFactory; import org.apache.ibatis.session.SqlSessionFactoryBuilder; public class MyBatisUtil { /** * 獲取SqlSessionFactory * @return SqlSessionFactory */ public static SqlSessionFactory getSqlSessionFactory() { String resource = "conf.xml" ; InputStream is = MyBatisUtil. class .getClassLoader().getResourceAsStream(resource); SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(is); return factory; } /** * 獲取SqlSession * @return SqlSession */ public static SqlSession getSqlSession() { return getSqlSessionFactory().openSession(); } /** * 獲取SqlSession * @param isAutoCommit * true 表示創建的SqlSession對象在執行完SQL之后會自動提交事務 * false 表示創建的SqlSession對象在執行完SQL之后不會自動提交事務,這時就需要我們手動調用sqlSession.commit()提交事務 * @return SqlSession */ public static SqlSession getSqlSession( boolean isAutoCommit) { return getSqlSessionFactory().openSession(isAutoCommit); } } |
以上的相關代碼是全部測試通過的,大家可以放心使用!
以上所述是小編給大家介紹的MyBatis學習教程(二)—如何使用MyBatis對users表執行CRUD操作,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復大家的。在此也非常感謝大家對服務器之家網站的支持!