spring和mybatis的整合开发(基于MapperScannerConfigurer的整合开发(适用于复杂项目,接口较多的情况))

在实际项目中,Dao层会包含很多接口,这样会导致spring配置文件过于臃肿。这时就需要采用扫描包的形式来配置mybaits中的映射器。

采用MapperScannerConfigurer来实现。

MapperScannerConfigurer类在spring配置文件中可以配置以下几个属性:

1.basePackage:用于指定映射接口文件的包路径,当需要扫描多个包时使用逗号或分号隔开。

2.annotationClass:指定了要扫描的注解名称,只有被注解标示的类才会被配置为映射器。

3.markerInterface:指定创建映射器的接口。

4.sqlSessionFactoryBeanName:指定在spring中定义的sqlSessionFactory的bean名称。

5.sqlSessionTemplateBeanName:指定在spring中定义的sqlSessionTemplate的bean名称。如果定义此属性,那么sqlSessionFactoryBeanName将不起作用。

例如:

CustomerMapper 接口,用@Repository表示此接口是一个dao层。
@Repository//标示是一个dao层
public interface CustomerMapper {
public Customer findCustomerById(Integer id);
}

mapper映射文件
<mapper namespace="com.itheima.po.mapper.CustomerMapper">
<select id="findCustomerById" parameterType="Integer" resultType="customer">
select * from t_customer where id=#{id}
</select>
</mapper>
在spring的配置文件中配置
<!--基于MapperScannerConfigurer的开发-->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.itheima.po.mapper"/>//用于扫描映射文件包,可以将映射文件放入不同的包中。
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>//value值是配置=mybatis工厂时的id值sqlSessionFactory
<property name="annotationClass" value="org.springframework.stereotype.Repository"/>//根据注解进行扫描,成mapper对象。
</bean>
最后测试,成功。
原文地址:https://www.cnblogs.com/jasonboren/p/10598083.html