前期準備
新建java工程或java wweb工程,需要導入以下的包,
基本工作已經完成,接下來開始進入正題。
新建實體類
新建與數據庫表對應的實體類
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
|
package com.edu.hpu.domain; /** * @author Administrator *user表所對應的實體類 */ public class User { //實體類的屬性和表的字段名稱一一對應 private int id; private String name; private int age; //對屬性進行封裝 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 int getAge() { return age; } public void setAge( int age) { this .age = age; } //添加toString方法 @Override public String toString() { return "User [id=" + id + ",name=" + name + ",age=" + age + "]" ; } } |
添加Mybatis工具類
添加用到的工具類,如下所示,
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 com.edu.hpu.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對數據進行增刪查改操作有兩種方法,分別為配置文件操作和注解操作。
通過配置文件進行操作
數據庫配置文件如下所示,對數據庫信息進行配置,
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
|
<?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.jdbc.Driver" /> <property name= "url" value= "jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=UTF-8&zeroDateTimeBehavior=convertToNull" /> <property name= "username" value= "root" /> <property name= "password" value= "admin" /> </dataSource> </environment> </environments> <mappers> <!-- 注冊userMapper.xml文件, userMapper.xml位于com.edu.hpu.mapping這個包下,所以resource寫成com/edu/hpu/mapping/userMapper.xml--> <mapper resource= "com/edu/hpu/mapping/userMapper.xml" /> <!-- <mapper class = "com.edu.hpu.mapping.UserMapper_11" /> --> </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
|
<?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.edu.hpu.mapping.userMapper" > <!-- 在select標簽中編寫查詢的SQL語句, 設置select標簽的id屬性為getUser,id屬性值必須是唯一的,不能夠重復 使用parameterType屬性指明查詢時使用的參數類型,resultType屬性指明查詢返回的結果集類型 resultType= "com.edu.hpu.domain.User" 就表示將查詢結果封裝成一個User類的對象返回 User類就是users表所對應的實體類 --> <!-- 根據id查詢得到一個user對象 --> <select id= "getUser" parameterType= "int" resultType= "com.edu.hpu.domain.User" > select * from users where id=#{id} </select> <!-- 創建用戶(Create) --> <insert id= "addUser" parameterType= "com.edu.hpu.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= "com.edu.hpu.domain.User" > update users set name=#{name},age=#{age} where id=#{id} </update> <!-- 查詢全部用戶--> <select id= "getAllUsers" resultType= "com.edu.hpu.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 com.edu.hpu.test; import java.util.List; import com.edu.hpu.domain.User; import com.edu.hpu.util.MyBatisUtil; import org.junit.Test; import org.apache.ibatis.session.SqlSession; public class Test2 { @Test public void testAdd(){ //SqlSession sqlSession = MyBatisUtil.getSqlSession(false); SqlSession sqlSession = MyBatisUtil.getSqlSession( true ); /** * 映射sql的標識字符串, * com.edu.hpu.mapping.userMapper是userMapper.xml文件中mapper標簽的namespace屬性的值, * addUser是insert標簽的id屬性值,通過insert標簽的id屬性值就可以找到要執行的SQL */ String statement = "com.edu.hpu.mapping.userMapper.addUser" ; //映射sql的標識字符串 User user = new User(); user.setName( "新增用戶小黃" ); user.setAge( 20 ); //執行插入操作 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的標識字符串, * com.edu.hpu.mapping.userMapper是userMapper.xml文件中mapper標簽的namespace屬性的值, * updateUser是update標簽的id屬性值,通過update標簽的id屬性值就可以找到要執行的SQL */ String statement = "com.edu.hpu.mapping.userMapper.updateUser" ; //映射sql的標識字符串 User user = new User(); user.setId( 3 ); user.setName( "hello world" ); user.setAge( 25 ); //執行修改操作 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的標識字符串, * com.edu.hpu.mapping.userMapper是userMapper.xml文件中mapper標簽的namespace屬性的值, * deleteUser是delete標簽的id屬性值,通過delete標簽的id屬性值就可以找到要執行的SQL */ String statement = "com.edu.hpu.mapping.userMapper.deleteUser" ; //映射sql的標識字符串 //執行刪除操作 int retResult = sqlSession.delete(statement, 4 ); //使用SqlSession執行完SQL之后需要關閉SqlSession sqlSession.close(); System.out.println(retResult); } @Test public void testGetAll(){ SqlSession sqlSession = MyBatisUtil.getSqlSession(); /** * 映射sql的標識字符串, * com.edu.hpu.mapping.userMapper是userMapper.xml文件中mapper標簽的namespace屬性的值, * getAllUsers是select標簽的id屬性值,通過select標簽的id屬性值就可以找到要執行的SQL */ String statement = "com.edu.hpu.mapping.userMapper.getAllUsers" ; //映射sql的標識字符串 //執行查詢操作,將查詢結果自動封裝成List<User>返回 List<User> lstUsers = sqlSession.selectList(statement); //使用SqlSession執行完SQL之后需要關閉SqlSession sqlSession.close(); System.out.println(lstUsers); } } |
通過注解進行操作
通過注解進行操作需要寫一個接口,但是不必實現,如下所示,
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 com.edu.hpu.mapping; import java.util.List; import com.edu.hpu.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 UserMapper_11 { //使用@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(); } |
同時,需要在數據庫配置文件中添加所寫的接口,在conf.xml中添加如下語句,
1
|
<mapper class = "com.edu.hpu.mapping.UserMapper_11" /> |
OK,基本上已經完成,這里給出測試類可以進行測試,
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
|
package com.edu.hpu.test; import java.util.List; import com.edu.hpu.domain.User; import com.edu.hpu.mapping.UserMapper_11; import com.edu.hpu.util.MyBatisUtil; import org.apache.ibatis.session.SqlSession; import org.junit.Test; /** * @author Administrator *對注解進行測試 */ public class Test3 { @Test public void testAdd(){ SqlSession sqlSession = MyBatisUtil.getSqlSession( true ); //得到UserMapper接口的實現類對象,UserMapper接口的實現類對象由sqlSession.getMapper(UserMapper.class)動態構建出來 UserMapper_11 mapper = sqlSession.getMapper(UserMapper_11. class ); User user = new User(); user.setName( "大智若愚" ); user.setAge( 20 ); int add = mapper.add(user); //使用SqlSession執行完SQL之后需要關閉SqlSession sqlSession.close(); System.out.println(add); } @Test public void testUpdate(){ SqlSession sqlSession = MyBatisUtil.getSqlSession( true ); //得到UserMapper接口的實現類對象,UserMapper接口的實現類對象由sqlSession.getMapper(UserMapper.class)動態構建出來 UserMapper_11 mapper = sqlSession.getMapper(UserMapper_11. class ); User user = new User(); user.setId( 3 ); user.setName( "大音希聲" ); user.setAge( 26 ); //執行修改操作 int retResult = mapper.update(user); //使用SqlSession執行完SQL之后需要關閉SqlSession sqlSession.close(); System.out.println(retResult); } @Test public void testDelete(){ SqlSession sqlSession = MyBatisUtil.getSqlSession( true ); //得到UserMapper接口的實現類對象,UserMapper接口的實現類對象由sqlSession.getMapper(UserMapper.class)動態構建出來 UserMapper_11 mapper = sqlSession.getMapper(UserMapper_11. class ); //執行刪除操作 int retResult = mapper.deleteById( 7 ); //使用SqlSession執行完SQL之后需要關閉SqlSession sqlSession.close(); System.out.println(retResult); } @Test public void testGetUser(){ SqlSession sqlSession = MyBatisUtil.getSqlSession(); //得到UserMapper接口的實現類對象,UserMapperI接口的實現類對象由sqlSession.getMapper(UserMapper.class)動態構建出來 UserMapper_11 mapper = sqlSession.getMapper(UserMapper_11. class ); //執行查詢操作,將查詢結果自動封裝成User返回 User user = mapper.getById( 1 ); //使用SqlSession執行完SQL之后需要關閉SqlSession sqlSession.close(); System.out.println(user); } @Test public void testGetAll(){ SqlSession sqlSession = MyBatisUtil.getSqlSession(); //得到UserMapper接口的實現類對象,UserMapper接口的實現類對象由sqlSession.getMapper(UserMapper.class)動態構建出來 UserMapper_11 mapper = sqlSession.getMapper(UserMapper_11. class ); //執行查詢操作,將查詢結果自動封裝成List<User>返回 List<User> lstUsers = mapper.getAll(); //使用SqlSession執行完SQL之后需要關閉SqlSession sqlSession.close(); System.out.println(lstUsers); } } |
以上所述是小編給大家介紹的mybatis實現對數據的增刪查改實例詳解,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復大家的。在此也非常感謝大家對服務器之家網站的支持!