【MyBatis】接口配合XML使用

前言

  MyBatis的真正强大之处在于它的映射语句,我们只需编写简单的XML文件。它提高了开发人员的效率。
  
  MyBatis3.0相比2.0版本的一个最大的变化,就是支持使用接口来调用方法。以前使用SqlSession通过命名空间调用MyBatis方法时,首先需要用到命名空间和方法id组成的字符串来调用相应的方法。当参数多于1个的时候,需要将所有参数放到一个Map对象中。通过Map传递多个参数,使用起来很不方便,而且还无法避免很多重复的代码。

  使用接口调用就会方便很多,MyBatis使用Java的动态代理可以直接通过接口来调用相应的方法,不需要提供接口的实现类。另外,当有多个参数的时候,通过参数注解@Param设置参数的名字省去了手动构造Map参数的过程,尤其在Spring中使用的时候,可以配置为自动扫描所有的接口类,直接将接口注入到需要的地方。

示例

//实体
public class TUser {

    private Long id;

    private String uName;

    private String uPassword;

}
//接口
public interface TUserMapper {

    int deleteByPrimaryKey(Long id);

    int insert(TUser record);

    TUser selectByPrimaryKey(Long id);

    List<TUser> selectAll();

    int updateByPrimaryKey(TUser record);

}
<!-- 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="cn.jujianfei.demo.dao.TUserMapper">

  <resultMap id="BaseResultMap" type="TUser">
    <id column="id" jdbcType="BIGINT" property="id" />
    <result column="u_name" jdbcType="VARCHAR" property="uName" />
    <result column="u_password" jdbcType="VARCHAR" property="uPassword" />
  </resultMap>

  <delete id="deleteByPrimaryKey" parameterType="java.lang.Long">
    delete from t_user
    where id = #{id,jdbcType=BIGINT}
  </delete>

  <insert id="insert" parameterType="TUser">
    insert into t_user (id, u_name, u_password)
    values (#{id,jdbcType=BIGINT}, #{uName,jdbcType=VARCHAR}, #{uPassword,jdbcType=VARCHAR})
  </insert>

  <update id="updateByPrimaryKey" parameterType="TUser">
    update t_user
    set u_name = #{uName,jdbcType=VARCHAR},
      u_password = #{uPassword,jdbcType=VARCHAR}
    where id = #{id,jdbcType=BIGINT}
  </update>

  <select id="selectByPrimaryKey" parameterType="java.lang.Long" resultMap="BaseResultMap">
    select id, u_name, u_password
    from t_user
    where id = #{id,jdbcType=BIGINT}
  </select>

  <select id="selectAll" resultMap="BaseResultMap">
    select id, u_name, u_password
    from t_user
  </select>

</mapper>
<!-- mybatis-config.xml -->
<?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>

    <!-- 在Mapper文件中使用实体类时不再需要使用全限定名。 -->
    <typeAliases>
        <package name="cn.jujianfei.demo.model"></package>
    </typeAliases>

    <environments default="development">
        <!-- 环境配置,即连接的数据库。 -->
        <environment id="development">
            <!--  指定事务管理类型,type="JDBC"指直接简单使用了JDBC的提交和回滚设置。 -->
            <transactionManager type="JDBC"/>
            <!--  dataSource指数据源配置,POOLED是JDBC连接对象的数据源连接池的实现。 -->
            <dataSource type="UNPOOLED">
                <property name="driver" value="com.mysql.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql://127.0.0.1:3306/mybatis"/>
                <property name="username" value="root"/>
                <property name="password" value="jujianfei"/>
            </dataSource>
        </environment>
    </environments>

    <!-- mappers告诉了MyBatis去哪里找持久化类的映射文件。 -->
    <mappers>
        <mapper resource="mapper/TUserMapper.xml"/>
    </mappers>

</configuration>
//测试类
public class AppTest 
{
    private static SqlSessionFactory sessionFactory;

    @BeforeClass
    public static void init(){
        try{
            Reader reader = Resources.getResourceAsReader("mybatis-config.xml");
            sessionFactory = new SqlSessionFactoryBuilder().build(reader);
            reader.close();
        }catch (IOException ignore){
            ignore.printStackTrace();
        }
    }

    @Test
    public void shouldAnswerWithTrue()
    {
        SqlSession sqlSession = sessionFactory.openSession();
        try{
            TUserMapper tUserMapper = sqlSession.getMapper(TUserMapper.class);
            int result = tUserMapper.deleteByPrimaryKey(new Long(1));
            //TUser result1 = tUserMapper.selectByPrimaryKey(new Long(2));
            //List<TUser> result2 = tUserMapper.selectAll();
            //......
            Assert.assertTrue(result>0);
        }finally {
            sqlSession.commit();
            sqlSession.close();
        }
    }
}

结语

  其中,示例中的SQL语句包括了这么一行代码:#{id,jdbcType=BIGINT},需要注意大括号里的键值对。
  
  说明:由于数据库区分date、time、datetime类型,但是Java中一般都使用java.util.Date类型。因此为了保证数据类型的正确,需要手动指定日期类型,date、time、datetime对应的JDBC类型分别为DATE、TIME、TIMESTAMP。

猜你喜欢

转载自blog.csdn.net/gnd15732625435/article/details/81192939