mybatis中<mappers> ,mapperLocations,和MapperScannerConfigurer 用法
mybatis中<mappers> ,mapperLocations,和MapperScannerConfigurer 用法
1. mappers標簽
在mybatis單獨使用時,mybatis需要在mybatis-config.xml中配置mappers。mappers 標簽下有許多 mapper 標簽,每一個 mapper 標簽中配置的都是一個獨立的映射配置文件的路徑,配置方式有以下幾種:
1.1 第一種方式:mapper標簽,通過resource屬性引入classpath路徑的相對資源
1.2mapper標簽,通過url引入網絡資源或者本地磁盤資源
<!-- Using url fully qualified paths --> <mappers><mapper url="file:///var/mappers/AuthorMapper.xml"/><mapper url="file:///var/mappers/BlogMapper.xml"/><mapper url="file:///var/mappers/PostMapper.xml"/> </mappers>1.3 第三種方式:mapper標簽,通過class屬性指定mapper接口名稱,此時對應的映射文件必須與接口位于同一路徑下,并且名稱相同
如mapper接口采用注解的方式,則無需映射文件
windows系統下,映射文件不區分大小寫,linux系統沒有驗證
1.4第四種方式:package標簽,通過name屬性指定mapper接口所在的包名 ,此時對應的映射文件必須與接口位于同一路徑下,并且名稱相同
如mapper接口采用注解的方式,則無需映射文件
windows系統下,映射文件不區分大小寫,linux系統沒有驗證
2. mapperLocation屬性(位于SqlSessionFactoryBean中):mapperLocation屬性,主要用于指定mapper.xml文件所處的位置。
2.1如果Mapper.xml與Mapper.class在同一個包下且同名,spring 中MapperScannerConfigurer 掃描Mapper.class的同時會自動掃描同名的Mapper.xml并裝配到Mapper.class。
2.2如果Mapper.xml與Mapper.class不在同一個包下或者不同名,就必須使用配置mapperLocations指定mapper.xml的位置。(如idea中 maven 默認不打包java文件夾下的xml文件,未在pom.xml中配置resource的情況下)
此時spring是通過識別mapper.xml中的
namespace的值來確定對應的Mapper.class的。
3. MapperScannerConfigurer:
自動掃描 將Mapper接口生成代理注入到Spring
3.1要創建 MapperScannerConfigurer,可以在 Spring 的配置中添加如下代碼:
basePackage 屬性是讓你為映射器接口文件設置基本的包路徑。 你可以使用分號或逗號 作為分隔符設置多于一個的包路徑。每個映射器將會在指定的包路徑中遞歸地被搜索到。
mybatis 整合spring之mapperLocations配置的問題
今天嘗試spring整合mybatis時遇到這么一個問題,就是在配置sqlSessionFactory時是否要配置mapperLocations的問題。
<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。
如果Mapper.xml與Mapper.class不在同一個包下或者不同名,就必須使用配置mapperLocations指定mapper.xml的位置。
此時spring是通過識別mapper.xml中的 namespace的值來確定對應的Mapper.class的。
創作挑戰賽新人創作獎勵來咯,堅持創作打卡瓜分現金大獎總結
以上是生活随笔為你收集整理的mybatis中<mappers> ,mapperLocations,和MapperScannerConfigurer 用法的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 机器学习实践:onnx模型转为Tenso
- 下一篇: 机器学习实践:本地远程查看服务器训练Te