mybatis的mapper

在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);
  
}

接下来要做的就是把Mapper信息注册到Mybatis的配置中,告诉Mybatis我们定义了哪些Mapper信息。这主要是在Mybatis的配置文件中通过mappers元素来进行的。在以前版本的Mybatis中我们在Mybatis的配置文件中需要这样定义Mapper信息资源的位置。

    <mappers>
       <mapper resource="com/tiantian/mybatis/mapper/UserMapper1.xml"/>
       <mapper url=">
    </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>

Java代码:

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属性来指定接口。

    <mappers>
       <mapper class="com.tiantian.mybatis.mapperinterface.UserMapper"/>
    </mappers>

这里的一个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=">
       <!-- 通过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();
              }
       }
     
}

 

 

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值