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