mybatis 整合spring之mapperLocations配置的問題

 今天嘗試spring整合mybatis時遇到這麼一個問題,就是在配置sqlSessionFactory時是否要配置mapperLocations的問題。spring

 

<bean id="sessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
    <property name="dataSource" ref="datasource"></property>
    <property name="typeAliasesPackage" value="com.fan.entity"/>
      <!-- 當mybatis的xml文件和mapper接口不在相同包下時,須要用mapperLocations屬性指定xml文件的路徑。  
         *是個通配符,表明全部的文件,**表明全部目錄下 -->   
    <property name="mapperLocations" value="classpath:com/fan/mapper/*.xml" /> 
   
    <!--也能夠引入mybatis配置文件 
        <property name="configLocation" value="classpath:mybatis/SqlMapConfig.xml"></property> -->
</bean>
<!-- 經過掃描的模式,掃描目錄在com.lanyuan.mapper目錄下的mapper-->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
    <property name="basePackage" value="com.fan.mapper"></property>
</bean>

 

結論是:若是Mapper.xml與Mapper.class在同一個包下且同名,spring掃描Mapper.class的同時會自動掃描同名的Mapper.xml並裝配到Mapper.class。sql

若是Mapper.xml與Mapper.class不在同一個包下或者不一樣名,就必須使用配置mapperLocations指定mapper.xml的位置。session

此時spring是經過識別mapper.xml中的 <mapper namespace="com.fan.mapper.UserDao"> namespace的值來肯定對應的Mapper.class的。mybatis

相關文章
相關標籤/搜索