前言
我们项目组的项目由于目前流量不大,因此所以功能模块都聚焦在一个项目里,没有做拆分,因此可能会比其他项目的坑多一点,最近接连在这个项目踩坑,这里记录一下xml扫描问题。
排查过程
现象,开发了一个联表查询 从mapper -> mapper.xml层,单元测的时候报:invalid bound statement (not found)
初步排查可能是以下原因
- *Mapper.class没有被扫描到
- *Mapper.xml没有被扫描到
- *Mapper.class没有和*Mapper.xml绑定成功
*Mapper.class没有被扫描到
排查关键字:@MapperScan || @MapperScans
@MapperScans
和@MapperScan
都是 MyBatis-Plus 框架中的注解,用于配置映射器扫描。@MapperScans
是 MyBatis-Plus 1.x 版本中的注解,主要作用是扫描指定包下的所有接口,而@MapperScan
是 MyBatis-Plus 3.x 版本中的注解,除了可以扫描指定包下的接口,还可以指定扫描器来自定义扫描方式。
结论:发现本项目使用的是@MapperScan,无异常,并且自定义了扫描方式
*Mapper.xml没有被扫描到
排查关键字:
如果是xml配置自动装配:mybatis.mapper-locations: classpath:/mapper/*.xml
如果是通过自定义扫描方式:setMapperLocations
classpath
表示一个具体的类路径,它包含一组具体的文件。例如,在Maven项目中,classpath
通常用于指定项目的依赖项。
classpath*
表示一个通配符类路径,它包含一个或多个通配符,用于匹配类路径中的所有文件。
// 以下是当前代码片段
Resource[] resources = new PathMatchingResourcePatternResolver().getResources("classpath:mybatis/*.xml")
bean.setMapperLocations(resources)
当前项目中存在多个module都包含了xml,所以需要设为
Resource[] resources = new PathMatchingResourcePatternResolver().getResources("classpath*:mybatis/*Mapper.xml");
*Mapper.class没有和*Mapper.xml绑定成功
排查关键字:
xml文件里填写的 <mapper namespace="com.XXXX.mapper.XXMapper">
在这次排查中了解到的小知识:
1.MyBatis的Mapper接口扫描方式主要有两种:基于XML的映射和基于Java的映射
<configuration>
<mappers>
<mapper resource="com/example/mappers/UserMapper.xml"/>
<mapper class="com.example.mappers.UserMapper"/>
</mappers>
</configuration>