在传统的DAO开发方式可以实现所需功能,但是采用这种方式在实现类中会出现大量的重复代码。在映射文件中执行语句的id,并不能保证编写时id的正确性(运行时才能知道),这时候,就用到了Mapper接口编程。
一、基于MapperFactoryBean的整合
1.在src目录下创建 com.kangxg.mapper 包 并创建CustomerMapper接口文件及CustomerMapper.xml映射文件
package com.kangxg.mapper;
import com.kangxg.po.Customer;
public interface CustomerMapper {
public Customer findCustomerById(Integer id);
}
<?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">
<!-- namespace 表示命名空间 -->
<mapper namespace="com.kangxg.mapper.CustomerMapper">
<!-- 根据客户编号获取客户信息 -->
<select id="findCustomerById" parameterType = "Integer" resultType="Customer">
select * from t_customer
where
id =#{id}
</select>
</mapper>
2.在MyBatis的配置文件中,引入新的映射文件
<mapper resource="com/kangxg/mapper/CustomerMapper.xml"/>
3.在Spring的配置文件中 增加相应的Bean
<bean id = "customerMapper" class ="org.mybatis.spring.mapper.MapperFactoryBean">
<property name="mapperInterface" value="com.kangxg.mapper.CustomerMapper"/>
<property name="sqlSessionFactory" ref ="sqlSessionFactory"/>
</bean>
4. 在测试文件中增加测试方法
@Test
public void findCustomerByIdMapperTest(){
String xmlPath = "applicationContext.xml";
ApplicationContext applicationContext = new ClassPathXmlApplicationContext(xmlPath);
CustomerMapper customerMapper = applicationContext.getBean(CustomerMapper.class);
Customer customer = customerMapper.findCustomerById(1);
System.out.println(customer);
}
5 debug junit 控制台输出结果
DEBUG [main] - ==> Preparing: select * from t_customer where id =?
DEBUG [main] - ==> Parameters: 1(Integer)
DEBUG [main] - <== Total: 1
Customer [id =1,username =kangxf, jobs =java, phone =13111111111]
总结 虽然使用Mapper 接口编程的方式很简单,但是在使用中必须遵循一下规范
- Mapper 接口的迷城和对应的Mapper.xml映射文件的名称一致
- Mapper.xml 文件中的namespace与Mapper接口的路径相同(即接口文件和映射文件需要放在同一个包中)
- Mapper接口中的方法名和Mapper.xml定义的每个执行语句的id相同
- Mapper接口中的方法的输入参数类型要和Mapper.xml中定义的每个sql的parameterType的类型相同
- Mapper接口方法的输出参数类型要和Mapper.xml中定义的每个sql的resultType的类型相同
二、基于MapperScannerConfiger的整合
使用 MapperScannerConfiger 非常简单只需要 Spring的配置文件中加入如下代码
<bean class ="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.kangxg.mapper"/>
</bean>
验证上面的配置 只需要把MapperFactoryBean 整合中的2、3 步骤代码注释即可。