Mybatis与Spring整合(二)
MapperScannerConfiger的整合
这篇博文是基于上一篇博客MyBatis与Spring整合继续进行的,前期配置可参考该博客
在src目录下创建com.mapper包,编写CustomerMapper接口以及对应的配置文件,编辑后如下所示
创建CustomerMapper.java,编写根据ID查找信息的方法
package com.mapper;
import com.po.Customer;
public interface CustomerMapper {
public Customer findCustomerById(Integer id);
}
编写CustomerMapper.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.mapper.CustomerMapper">
<!--根据id查询客户信息 -->
<select id="findCustomerById" parameterType="Integer"
resultType="customer">
select * from t_customer where id = #{id}
</select>
<!--添加客户信息 -->
<insert id="addCustomer" parameterType="customer">
insert into t_customer(username,jobs,phone)
values(#{username},#{jobs},#{phone})
</insert>
</mapper>
基于MapperScannerConfigure的整合
MapperScannerConfigure的使用很简单,只需在spring的配置文件applicationContext.xml中添加如下代码
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.mapper" />
</bean>
其中basePackage是制定映射接口所在包的路径,指定包路径后,会扫描该包及其子包中的所有文件
整合测试
在测试类DaoTest中编写测试方法findCustomerByIdMapperTest()方法,如下
public void findCustomerByIdMapperTest(){
ApplicationContext act =
new ClassPathXmlApplicationContext("applicationContext.xml");
CustomerMapper customerMapper = act.getBean(CustomerMapper.class);
Customer customer = customerMapper.findCustomerById(1);
System.out.println(customer);
}
运行结果如下
写在最后
MapperScannerConfigure在使用时只需通过basePackage属性制定需要扫描的包,Spring会自动的通过包中的接口来生成映射器,从而提高开发效率。