我們在做Spring和Mbatis集成的時候,需要在配置中配置mapperLocations.
我需要加載多個包下的mapper.xml文件.
比如加載cn/wolfcode/base/mapper
文件夾和cn/wolfcode/bussiness/mapper
文件夾下所有的mapper.xml文件.
一開始文件配置如下:
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="configLocation" value="classpath:mybatis-config.xml" />
<property name="typeAliasesPackage" value="cn.wolfcode.base.domain;cn.wolfcode.business.domain" />
<property name="mapperLocations" value="classpath:cn/wolfcode/*/mapper/*Mapper.xml;" />
</bean>
結果一直報cn/wolfcode/base/mapper下的mapper文件的某個方法找不到.
錯誤:Invalid bound statement (not found)
修改成這樣就可以找到了.
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="configLocation" value="classpath:mybatis-config.xml" />
<property name="typeAliasesPackage" value="cn.wolfcode.base.domain;cn.wolfcode.business.domain" />
<property name="mapperLocations" value="classpath*:cn/wolfcode/*/mapper/*Mapper.xml;" />
</bean>
原因是classpath:和classpath*:在spring加載資源的時候是不同的.
classpath
:只能加載找到的匹配的第一個資源目錄下文件.(上面只匹配了cn/wolfcode/bussiness/mapper下的mapper文件,而cn/wolfcode/base/mapper就被忽略了)
classpath*
:能加載多個路徑下的資源目錄下文件.(cn/wolfcode/bussiness/mapper和cn/wolfcode/base/mapper中的mapper.xml文件都被加載進來了.)