Spring集成Mybatis配置映射文件方法详解

Spring ORM模块集成Mybatis使用到了mybatis-spring,在配置mybatis映射文件的时候,一般不直接在Mybatis的配置文件里进行配置,而会在Spring的配置文件里使用MapperScannerConfigurer来配置。MapperScannerConfigurer会自动扫描basePackage指定的包,找到映射接口类和映射XML文件,并进行注入。


Spring的配置文件applicationContext.xml内容如下:

<!--  扫描 mappers 自动配置 -->      
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">    
    	<property name="basePackage" value="com.guowei.maven.framework.dao" />      
    </bean>  
    
    <bean id="configProperties" class="org.springframework.beans.factory.config.PropertiesFactoryBean">
        <property name="locations">
            <list>
                <value>classpath:mysqldb.properties</value>
            </list>
        </property>
    </bean>
    <bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
        <property name="ignoreResourceNotFound" value="false" />
        <property name="properties" ref="configProperties" />
    </bean>
    
	<bean id="dataSource" class="org.apache.commons.dbcp2.BasicDataSource">
		<property name="driverClassName" value="${driver}" />
		<property name="url" value="${url}" />
		<property name="username" value="${username}" />
		<property name="password" value="${password}" />
	</bean>
	
	<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
		<!--dataSource属性指定要用到的连接池-->
		<property name="dataSource" ref="dataSource" />
		<!--configLocation属性指定mybatis的核心配置文件-->
		<property name="configLocation" value="mybatisconf.xml" />
	</bean>

但是,进行这个配置的前提条件是:映射接口类文件(.java)和映射XML文件(.xml)需要放在相同的包下,比如:com.guowei.test.mapper。

如果Mybatis映射XML文件和映射接口文件不放在同一个包下,那就还需要在上面的基础上,手动配置SqlSessionFactoryBean的mapperLocations属性,如下所示:

<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
		<!--dataSource属性指定要用到的连接池-->
		<property name="dataSource" ref="dataSource" />
		<!--configLocation属性指定mybatis的核心配置文件-->
		<property name="configLocation" value="mybatisconf.xml" />
		<!--mapperLocations属性指定mybatis的映射文件-->
		<property name="mapperLocations" value="classpath*:com/guowei/maven/framework/**/*.xml" />
</bean>

需要添加一个mapperLocations属性,指定加载xml文件的路径。

classpath:表示在classes目录中查找;

*:通配符表示所有文件;

**:表示所有目录下;


参考Mybatis官网说明如下:http://mybatis.github.io/spring/factorybean.html


你可能感兴趣的:(spring,mybatis)