现假设我有这样一个实体类:
Java代码
1. package com.tiantian.mybatis.model;
2.
3. public class User {
4.
5. private int id;
6. private String name;
7. private int age;
8. public int getId() {
9. return id;
10. }
11. public void setId(int id) {
12. this.id = id;
13. }
14. public String getName() {
15. return name;
16. }
17. public void setName(String name) {
18. this.name = name;
19. }
20. public int getAge() {
21. return age;
22. }
23. public void setAge(int age) {
24. this.age = age;
25. }
26.
27. }
package com.tiantian.mybatis.model; 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; } }
它对应的数据库表结构是这样的:
然后我要利用Mybatis对它做一个简单的增删改查操作,那么如果利用xml配置Mapper的方式来定义的话,我对应的UserMapper.xml文件会是这样:
Xml代码
1. <?xml version="1.0" encoding="UTF-8" ?>
2. <!DOCTYPE mapper
3. PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
4. "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
5.
6. <mapper namespace="com.tiantian.mybatis.mapper.UserMapper">
7. <insert id="insertUser" parameterType="User" useGeneratedKeys="true" keyColumn="id">
8. insert into t_user(name, age) values(#{name}, #{age})
9. </insert>
10.
11. <update id="updateUser" parameterType="User">
12. update t_user set name=#{name}, age=#{age} where id=#{id}
13. </update>
14.
15. <select id="findById" parameterType="int" resultType="User">
16. select * from t_user where id=#{id}
17. </select>
18.
19. <delete id="deleteUser" parameterType="int">
20. delete from t_user where id=#{id}
21. </delete>
22. </mapper>
<?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.tiantian.mybatis.mapper.UserMapper"> <insert id="insertUser" parameterType="User" useGeneratedKeys="true" keyColumn="id"> insert into t_user(name, age) values(#{name}, #{age}) </insert> <update id="updateUser" parameterType="User"> update t_user set name=#{name}, age=#{age} where id=#{id} </update> <select id="findById" parameterType="int" resultType="User"> select * from t_user where id=#{id} </select> <delete id="deleteUser" parameterType="int"> delete from t_user where id=#{id} </delete></mapper>
如果使用接口加注解的方式,那么我们的UserMapper接口应该这样定义:
Java代码
1. package com.tiantian.mybatis.mapperinterface;
2.
3. import org.apache.ibatis.annotations.Delete;
4. import org.apache.ibatis.annotations.Insert;
5. import org.apache.ibatis.annotations.Select;
6. import org.apache.ibatis.annotations.Update;
7.
8. import com.tiantian.mybatis.model.User;
9.
10. public interface UserMapper {
11.
12. @Insert("insert into t_user(name, age) values(#{name}, #{age})")
13. public void insertUser(User user);
14.
15. @Update("update t_user set name=#{name}, age=#{age} where id=#{id}")
16. public void updateUser(User user);
17.
18. @Select("select * from t_user where id=#{id}")
19. public User findById(int id);
20.
21. @Delete("delete from t_user where id=#{id}")
22. public void deleteUser(int id);
23.
24. }
package com.tiantian.mybatis.mapperinterface; import org.apache.ibatis.annotations.Delete;import org.apache.ibatis.annotations.Insert;import org.apache.ibatis.annotations.Select;import org.apache.ibatis.annotations.Update; import com.tiantian.mybatis.model.User; public interface UserMapper { @Insert("insert into t_user(name, age) values(#{name}, #{age})") public void insertUser(User user); @Update("update t_user set name=#{name}, age=#{age} where id=#{id}") public void updateUser(User user); @Select("select * from t_user where id=#{id}") public User findById(int id); @Delete("delete from t_user where id=#{id}") public void deleteUser(int id); }
注意看这里我故意把UserMapper接口的namespace也就是它的包名置为与UserMapper.xml的namespace属性不一样。这主要是为了要更好的讲以下的内容。
接下来要做的就是把Mapper信息注册到Mybatis的配置中,告诉Mybatis我们定义了哪些Mapper信息。这主要是在Mybatis的配置文件中通过mappers元素来进行的。在以前版本的Mybatis中我们在Mybatis的配置文件中需要这样定义Mapper信息资源的位置。
Xml代码
1. <mappers>
2. <mapper resource="com/tiantian/mybatis/mapper/UserMapper1.xml"/>
3. <mapper url="file:///E:/UserMapper.xml"/>
4. </mappers>
<mappers> <mapper resource="com/tiantian/mybatis/mapper/UserMapper1.xml"/> <mapper url="file:///E:/UserMapper.xml"/> </mappers>
这主要是通过mapper元素的resource和url属性来指定的,resource属性指定的是相对于跟类路径下的资源,url属性指定的是通过URL可以获取到的资源。这有一点不好的地方,当我们使用Mapper接口加注解来定义当前Mapper的操作信息时,我们还需要定义一个与它对应的Mapper.xml文件。如:
Xml代码
1. <?xml version="1.0" encoding="UTF-8" ?>
2. <!DOCTYPE mapper
3. PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
4. "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
5. <mapper namespace="com.tiantian.mybatis.mapperinterface.UserMapper">
6.
7. </mapper>
<?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.tiantian.mybatis.mapperinterface.UserMapper"> </mapper>
Java代码
1. package com.tiantian.mybatis.mapperinterface;
2.
3. import org.apache.ibatis.annotations.Delete;
4. import org.apache.ibatis.annotations.Insert;
5. import org.apache.ibatis.annotations.Select;
6. import org.apache.ibatis.annotations.Update;
7.
8. import com.tiantian.mybatis.model.User;
9.
10. public interface UserMapper {
11.
12. @Insert("insert into t_user(name, age) values(#{name}, #{age})")
13. public void insertUser(User user);
14.
15. @Update("update t_user set name=#{name}, age=#{age} where id=#{id}")
16. public void updateUser(User user);
17.
18. @Select("select * from t_user where id=#{id}")
19. public User findById(int id);
20.
21. @Delete("delete from t_user where id=#{id}")
22. public void deleteUser(int id);
23.
24. }
package com.tiantian.mybatis.mapperinterface; import org.apache.ibatis.annotations.Delete;import org.apache.ibatis.annotations.Insert;import org.apache.ibatis.annotations.Select;import org.apache.ibatis.annotations.Update; import com.tiantian.mybatis.model.User; public interface UserMapper { @Insert("insert into t_user(name, age) values(#{name}, #{age})") public void insertUser(User user); @Update("update t_user set name=#{name}, age=#{age} where id=#{id}") public void updateUser(User user); @Select("select * from t_user where id=#{id}") public User findById(int id); @Delete("delete from t_user where id=#{id}") public void deleteUser(int id); }
我发现在现在使用的这个Mybatis3.2.1中这个问题已经得到了改善,现在我们在定义基于接口的定义的Mapper时可以通过一个class属性来指定接口。
Xml代码
1. <mappers>
2. <mapper class="com.tiantian.mybatis.mapperinterface.UserMapper"/>
3. </mappers>
<mappers> <mapper class="com.tiantian.mybatis.mapperinterface.UserMapper"/> </mappers>
除了通过class属性指定Mapper接口外,Mybatis还为我们提供了一个可以同时指定多个Mapper接口的方法。在现在的Mybatis版本中我们可以在mappers元素下面定义一个package子元素,用以指定Mapper接口所在的包,这样Mybatis就会把这个包下面的所有Mapper接口都进行注册。
Xml代码
1. <mappers>
2. <package name="com.tiantian.mybatis.mapperinterface"/>
3. </mappers>
<mappers> <package name="com.tiantian.mybatis.mapperinterface"/> </mappers>
这里的一个package只针对于一个包。当在多个包里面定义有Mapper接口时,我们需要定义对应的多个package元素。
这四种注册Mapper的方式就是我想在这篇文章中表达的。总结一下:
Xml代码
1. <mappers>
2. <!-- 通过package元素将会把指定包下面的所有Mapper接口进行注册 -->
3. <package name="com.tiantian.mybatis.mapperinterface"/>
4. <!-- 通过mapper元素的resource属性可以指定一个相对于类路径的Mapper.xml文件 -->
5. <mapper resource="com/tiantian/mybatis/mapper/UserMapper.xml"/>
6. <!-- 通过mapper元素的url属性可以指定一个通过URL请求道的Mapper.xml文件 -->
7. <mapper url="file:///E:/UserMapper.xml"/>
8. <!-- 通过mapper元素的class属性可以指定一个Mapper接口进行注册 -->
9. <mapper class="com.tiantian.mybatis.mapperinterface.UserMapper"/>
10. </mappers>
<mappers> <!-- 通过package元素将会把指定包下面的所有Mapper接口进行注册 --> <package name="com.tiantian.mybatis.mapperinterface"/> <!-- 通过mapper元素的resource属性可以指定一个相对于类路径的Mapper.xml文件 --> <mapper resource="com/tiantian/mybatis/mapper/UserMapper.xml"/> <!-- 通过mapper元素的url属性可以指定一个通过URL请求道的Mapper.xml文件 --> <mapper url="file:///E:/UserMapper.xml"/> <!-- 通过mapper元素的class属性可以指定一个Mapper接口进行注册 --> <mapper class="com.tiantian.mybatis.mapperinterface.UserMapper"/> </mappers>
当使用mapper元素进行Mapper定义的时候需要注意:mapper的三个属性resource、url和class对于每个mapper元素只能指定一个,要么指定resource属性,要么指定url属性,要么指定class属性,不能都指定,也不能都不指定。
下面将对上面的代码给出一些对应的测试代码。先贴出测试对应的Mybatis的配置文件:
Xml代码
1. <?xml version="1.0" encoding="UTF-8" ?>
2. <!DOCTYPE configuration
3. PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
4. "http://mybatis.org/dtd/mybatis-3-config.dtd">
5. <configuration>
6.
7. <properties resource="config/jdbc.properties"></properties>
8. <typeAliases>
9. <package name="com.tiantian.mybatis.model"/>
10. </typeAliases>
11. <environments default="development">
12. <environment id="development">
13. <transactionManager type="JDBC" />
14. <dataSource type="POOLED">
15. <property name="driver" value="${jdbc.driver}" />
16. <property name="url" value="${jdbc.url}" />
17. <property name="username" value="${jdbc.username}" />
18. <property name="password" value="${jdbc.password}" />
19. </dataSource>
20. </environment>
21. </environments>
22. <mappers>
23. <package name="com.tiantian.mybatis.mapperinterface"/>
24. <mapper resource="com/tiantian/mybatis/mapper/UserMapper.xml"/>
25. </mappers>
26. </configuration>
<?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> <properties resource="config/jdbc.properties"></properties> <typeAliases> <package name="com.tiantian.mybatis.model"/> </typeAliases> <environments default="development"> <environment id="development"> <transactionManager type="JDBC" /> <dataSource type="POOLED"> <property name="driver" value="${jdbc.driver}" /> <property name="url" value="${jdbc.url}" /> <property name="username" value="${jdbc.username}" /> <property name="password" value="${jdbc.password}" /> </dataSource> </environment> </environments> <mappers> <package name="com.tiantian.mybatis.mapperinterface"/> <mapper resource="com/tiantian/mybatis/mapper/UserMapper.xml"/> </mappers></configuration>
1.对于使用xml方式定义的UserMapper.xml,然后直接使用SqlSession访问定义在其中的statement的测试:
Java代码
1. package com.tiantian.mybatis.test;
2.
3. import org.apache.ibatis.session.SqlSession;
4. import org.apache.ibatis.session.SqlSessionFactory;
5. import org.junit.Before;
6. import org.junit.Test;
7.
8. import com.tiantian.mybatis.model.User;
9. import com.tiantian.mybatis.util.Util;
10.
11. /**
12. *
13. * 这个类主要用来测试直接使用SqlSession访问定义在UserMapper.xml文件中的statement
14. *
15. */
16. public class UserMapperTest {
17.
18. SqlSessionFactory sqlSessionFactory = null;
19.
20. @Before
21. public void before() {
22. sqlSessionFactory = Util.getSqlSessionFactory();
23. }
24.
25. @Test
26. public void testInsert() {
27. SqlSession sqlSession = sqlSessionFactory.openSession();
28. try {
29. User user = new User();
30. user.setName("张三");
31. user.setAge(30);
32. sqlSession.insert("com.tiantian.mybatis.mapper.UserMapper.insertUser", user);
33. sqlSession.commit();
34. } finally {
35. sqlSession.close();
36. }
37. }
38.
39. @Test
40. public void testUpdate() {
41. SqlSession sqlSession = sqlSessionFactory.openSession();
42. try {
43. User user = new User();
44. user.setId(1);
45. user.setName("李四");
46. user.setAge(34);
47. sqlSession.update("com.tiantian.mybatis.mapper.UserMapper.updateUser", user);
48. sqlSession.commit();
49. } finally {
50. sqlSession.close();
51. }
52. }
53.
54. @Test
55. public void testFind() {
56. SqlSession sqlSession = sqlSessionFactory.openSession();
57. try {
58. User user = sqlSession.selectOne("com.tiantian.mybatis.mapper.UserMapper.findById", 1);
59. System.out.println(user.getId() + "--" + user.getName() + "--" + user.getAge());
60. } finally {
61. sqlSession.close();
62. }
63. }
64.
65. @Test
66. public void testDelele() {
67. SqlSession sqlSession = sqlSessionFactory.openSession();
68. try {
69. sqlSession.delete("com.tiantian.mybatis.mapper.UserMapper.deleteUser", 2);
70. sqlSession.commit();
71. } finally {
72. sqlSession.close();
73. }
74. }
75.
76. }
package com.tiantian.mybatis.test; import org.apache.ibatis.session.SqlSession;import org.apache.ibatis.session.SqlSessionFactory;import org.junit.Before;import org.junit.Test; import com.tiantian.mybatis.model.User;import com.tiantian.mybatis.util.Util; /** * * 这个类主要用来测试直接使用SqlSession访问定义在UserMapper.xml文件中的statement * */public class UserMapperTest { SqlSessionFactory sqlSessionFactory = null; @Before public void before() { sqlSessionFactory = Util.getSqlSessionFactory(); } @Test public void testInsert() { SqlSession sqlSession = sqlSessionFactory.openSession(); try { User user = new User(); user.setName("张三"); user.setAge(30); sqlSession.insert("com.tiantian.mybatis.mapper.UserMapper.insertUser", user); sqlSession.commit(); } finally { sqlSession.close(); } } @Test public void testUpdate() { SqlSession sqlSession = sqlSessionFactory.openSession(); try { User user = new User(); user.setId(1); user.setName("李四"); user.setAge(34); sqlSession.update("com.tiantian.mybatis.mapper.UserMapper.updateUser", user); sqlSession.commit(); } finally { sqlSession.close(); } } @Test public void testFind() { SqlSession sqlSession = sqlSessionFactory.openSession(); try { User user = sqlSession.selectOne("com.tiantian.mybatis.mapper.UserMapper.findById", 1); System.out.println(user.getId() + "--" + user.getName() + "--" + user.getAge()); } finally { sqlSession.close(); } } @Test public void testDelele() { SqlSession sqlSession = sqlSessionFactory.openSession(); try { sqlSession.delete("com.tiantian.mybatis.mapper.UserMapper.deleteUser", 2); sqlSession.commit(); } finally { sqlSession.close(); } } }
2.对于使用Mapper接口加对应的注解来定义的Mapper信息直接使用SqlSession访问Mapper接口中使用注解定义好的statement的测试:
Java代码
1. package com.tiantian.mybatis.test;
2.
3. import org.apache.ibatis.session.SqlSession;
4. import org.apache.ibatis.session.SqlSessionFactory;
5. import org.junit.Before;
6. import org.junit.Test;
7.
8. import com.tiantian.mybatis.model.User;
9. import com.tiantian.mybatis.util.Util;
10.
11. /**
12. *
13. *这个类是测试直接使用SqlSession访问UserMapper接口中使用注解定义好的statement
14. *
15. */
16. public class UserMapperTest2 {
17.
18. SqlSessionFactory sqlSessionFactory = null;
19.
20. @Before
21. public void before() {
22. sqlSessionFactory = Util.getSqlSessionFactory();
23. }
24.
25. @Test
26. public void testInsert() {
27. SqlSession sqlSession = sqlSessionFactory.openSession();
28. try {
29. User user = new User();
30. user.setName("张三");
31. user.setAge(30);
32. sqlSession.insert("com.tiantian.mybatis.mapperinterface.UserMapper.insertUser", user);
33. sqlSession.commit();
34. } finally {
35. sqlSession.close();
36. }
37. }
38.
39. @Test
40. public void testUpdate() {
41. SqlSession sqlSession = sqlSessionFactory.openSession();
42. try {
43. User user = new User();
44. user.setId(1);
45. user.setName("李四");
46. user.setAge(34);
47. sqlSession.update("com.tiantian.mybatis.mapperinterface.UserMapper.updateUser", user);
48. sqlSession.commit();
49. } finally {
50. sqlSession.close();
51. }
52. }
53.
54. @Test
55. public void testFind() {
56. SqlSession sqlSession = sqlSessionFactory.openSession();
57. try {
58. User user = sqlSession.selectOne("com.tiantian.mybatis.mapperinterface.UserMapper.findById", 1);
59. System.out.println(user.getId() + "--" + user.getName() + "--" + user.getAge());
60. } finally {
61. sqlSession.close();
62. }
63. }
64.
65. @Test
66. public void testDelele() {
67. SqlSession sqlSession = sqlSessionFactory.openSession();
68. try {
69. sqlSession.delete("com.tiantian.mybatis.mapperinterface.UserMapper.deleteUser", 3);
70. sqlSession.commit();
71. } finally {
72. sqlSession.close();
73. }
74. }
75.
76. }
package com.tiantian.mybatis.test; import org.apache.ibatis.session.SqlSession;import org.apache.ibatis.session.SqlSessionFactory;import org.junit.Before;import org.junit.Test; import com.tiantian.mybatis.model.User;import com.tiantian.mybatis.util.Util; /** * *这个类是测试直接使用SqlSession访问UserMapper接口中使用注解定义好的statement * */public class UserMapperTest2 { SqlSessionFactory sqlSessionFactory = null; @Before public void before() { sqlSessionFactory = Util.getSqlSessionFactory(); } @Test public void testInsert() { SqlSession sqlSession = sqlSessionFactory.openSession(); try { User user = new User(); user.setName("张三"); user.setAge(30); sqlSession.insert("com.tiantian.mybatis.mapperinterface.UserMapper.insertUser", user); sqlSession.commit(); } finally { sqlSession.close(); } } @Test public void testUpdate() { SqlSession sqlSession = sqlSessionFactory.openSession(); try { User user = new User(); user.setId(1); user.setName("李四"); user.setAge(34); sqlSession.update("com.tiantian.mybatis.mapperinterface.UserMapper.updateUser", user); sqlSession.commit(); } finally { sqlSession.close(); } } @Test public void testFind() { SqlSession sqlSession = sqlSessionFactory.openSession(); try { User user = sqlSession.selectOne("com.tiantian.mybatis.mapperinterface.UserMapper.findById", 1); System.out.println(user.getId() + "--" + user.getName() + "--" + user.getAge()); } finally { sqlSession.close(); } } @Test public void testDelele() { SqlSession sqlSession = sqlSessionFactory.openSession(); try { sqlSession.delete("com.tiantian.mybatis.mapperinterface.UserMapper.deleteUser", 3); sqlSession.commit(); } finally { sqlSession.close(); } } }
3.对于使用Mapper接口加注解定义好的Mapper信息通过SqlSession获取其对应的Mapper接口来操作其中定义好的statement的测试:
Java代码
1. package com.tiantian.mybatis.test;标签:Mapper,配置,id,mybatis,sqlSession,user,Mybatis,import,public From: https://blog.51cto.com/u_4172728/5997178
2.
3. import org.apache.ibatis.session.SqlSession;
4. import org.apache.ibatis.session.SqlSessionFactory;
5. import org.junit.Before;
6. import org.junit.Test;
7.
8. import com.tiantian.mybatis.mapperinterface.UserMapper;
9. import com.tiantian.mybatis.model.User;
10. import com.tiantian.mybatis.util.Util;
11.
12. /**
13. *
14. *这个类是测试使用SqlSession获取UserMapper接口来执行使用注解定义在UserMapper接口中的statement
15. *
16. */
17. public class UserMapperTest3 {
18.
19. SqlSessionFactory sqlSessionFactory = null;
20.
21. @Before
22. public void before() {
23. sqlSessionFactory = Util.getSqlSessionFactory();
24. }
25.
26. @Test
27. public void testInsert() {
28. SqlSession sqlSession = sqlSessionFactory.openSession();
29. try {
30. User user = new User();
31. user.setName("张三");
32. user.setAge(30);
33. UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
34. userMapper.insertUser(user);
35. sqlSession.commit();
36. } finally {
37. sqlSession.close();
38. }
39. }
40.
41. @Test
42. public void testUpdate() {
43. SqlSession sqlSession = sqlSessionFactory.openSession();
44. try {
45. User user = new User();
46. user.setId(1);
47. user.setName("李四");
48. user.setAge(34);
49. UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
50. userMapper.updateUser(user);
51. sqlSession.commit();
52. } finally {
53. sqlSession.close();
54. }
55. }
56.
57. @Test
58. public void testFind() {
59. SqlSession sqlSession = sqlSessionFactory.openSession();
60. try {
61. UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
62. User user = userMapper.findById(1);
63. System.out.println(user.getId() + "--" + user.getName() + "--" + user.getAge());
64. } finally {
65. sqlSession.close();
66. }
67. }
68.
69. @Test
70. public void testDelele() {
71. SqlSession sqlSession = sqlSessionFactory.openSession();
72. try {
73. UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
74. userMapper.deleteUser(5);
75. sqlSession.commit();
76. } finally {
77. sqlSession.close();
78. }
79. }
80.
81. }