mybatis整合spring開啟mapper.xml映射文件掃描
一般情況下,我們知道在使用mybatis的時候,必須在mybatis全局配置文件里配置映射文件。
代碼如下:
1
2
3
4
5
6
7
8
9
|
< mappers > < mapper resource = "/resources/mybatis/sys/ParamMapper.xml" /> < mapper resource = "/resources/mybatis/account/UmUserDevMapper.xml" /> < mapper resource = "/resources/mybatis/authz/AcctAuthorityMapper.xml" /> < mapper resource = "/resources/mybatis/authz/ApplicationMapper.xml" /> < mapper resource = "/resources/mybatis/authn/LoginMapper.xml" /> < mapper resource = "/resources/mybatis/audit/LogLoginMapper.xml" /> < mapper resource = "/resources/mybatis/audit/LogActionMapper.xml" /> </ mappers > |
但是與spring整合后,spring提供了mapperLocations屬性來掃描指定路徑下的映射文件。于是就可以省去每增加一個映射文件就要在mybatis-config.xml文件加一個配置的麻煩。
1
2
3
4
5
6
7
|
<!-- 配置mybatis --> < bean id = "sqlSessionFactory" class = "org.mybatis.spring.SqlSessionFactoryBean" > < property name = "dataSource" ref = "dataSource" /> < property name = "configLocation" value = "classpath:resources/mybatis/mybatis-config2.xml" ></ property > <!-- mapper掃描 --> < property name = "mapperLocations" value = "classpath:resources/mybatis/entity/*.xml" ></ property > </ bean > |
spring配置掃描mybatis的mapper文件注意
一般會將不業務的mapper文件放到不同的包中:
spring配置掃描就需要配置下面的方式(兩個*):
1
2
3
4
|
<!-- mybatis文件配置,掃描所有mapper文件 --> < bean id = "sqlSessionFactory" class = "org.mybatis.spring.SqlSessionFactoryBean" p:dataSource-ref = "dataSource" p:configLocation = "classpath:conf/mybatis-config.xml" p:mapperLocations = "classpath:mapper/**/*.xml" /> |
以上為個人經驗,希望能給大家一個參考,也希望大家多多支持服務器之家。
原文鏈接:https://blog.csdn.net/lycyl/article/details/88615312