Mybatis中配置Mapper的方法
在这篇文章中我主要想讲一下Mybatis配置文件里mappers元素的配置。
关于基础部分的内容能够參考http://blog.csdn.net/elim168/article/details/40622491。
我们知道在Mybatis中定义Mapper信息有两种方式,一种是利用xml写一个对应的包括Mapper信息的配置文件;还有一种就是定义一个Mapper接口,然后定义一些对应的操作方法,再辅以对应的操作注解。
现如果我有这样一个实体类:
- 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 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接口应该这样定义:
- 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信息资源的位置。
- <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 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>
- 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属性来指定接口。
除了通过class属性指定Mapper接口外。Mybatis还为我们提供了一个能够同一时候指定多个Mapper接口的方法。在如今的Mybatis版本号中我们能够在mappers元素以下定义一个package子元素,用以指定Mapper接口所在的包,这样Mybatis就会把这个包以下的全部Mapper接口都进行注冊。
这里的一个package仅仅针对于一个包。当在多个包里面定义有Mapper接口时,我们须要定义相应的多个package元素。
这四种注冊Mapper的方式就是我想在这篇文章中表达的。总结一下:
- <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 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>
- <mapper resource="com/tiantian/mybatis/mapper/UserMapper.xml"/>
- <package name="com.tiantian.mybatis.mapperinterface"/>
- </mappers>
- </configuration>
1.对于使用xml方式定义的UserMapper.xml,然后直接使用SqlSession訪问定义在当中的statement的測试:
- 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的測试:
- 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的測试:
- 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.mapperinterface.UserMapper;
- import com.tiantian.mybatis.model.User;
- import com.tiantian.mybatis.util.Util;
- /**
- *
- *这个类是測试使用SqlSession获取UserMapper接口来运行使用注解定义在UserMapper接口中的statement
- *
- */
- public class UserMapperTest3 {
- 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);
- UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
- 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);
- UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
- userMapper.updateUser(user);
- sqlSession.commit();
- } finally {
- sqlSession.close();
- }
- }
- @Test
- public void testFind() {
- SqlSession sqlSession = sqlSessionFactory.openSession();
- try {
- UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
- User user = userMapper.findById(1);
- System.out.println(user.getId() + "--" + user.getName() + "--" + user.getAge());
- } finally {
- sqlSession.close();
- }
- }
- @Test
- public void testDelele() {
- SqlSession sqlSession = sqlSessionFactory.openSession();
- try {
- UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
- userMapper.deleteUser(5);
- sqlSession.commit();
- } finally {
- sqlSession.close();
- }
- }
- }