Spring配置MyBatis

时间:2024-08-23 18:38:14

1.MyBatis配置文件(mybatis-config)

<?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>
<mappers></mappers>
</configuration>

2.Spring配置sqlSessionFactory

<bean id="sqlSessionFactory"
class="org.mybatis.spring.SqlSessionFactoryBean"
p:dataSource-ref="dataSource"
p:configLocation="classpath:conf/mybatis-config.xml"
p:mapperLocations="classpath:com/**/dao/sql/*xml"/>

configLocation:MyBatis配置文件路径;

SqlSessionFactoryBean提供了mapperLocations属性,支持扫描式加载SQL映射文件;

3.Spring配置MapperScannerConfigurer

<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"
p:basePackage="com.dogstore.dao"/>

MapperScannerConfigurer将扫描basePackage所指定的报下所有接口类,如果他们在SQL映射文件中定义过,则将他们动态定义为一个Spring Bean。这样,我们就可以在Service直接注入映射接口的Bean了。