Springboot 多模块项目使用mybatis-plus插件,调用sql时报错:Invalid bound statement (not found)
Springboot 多模块项目,整合mybatis-plus报错:Invalid bound statement (not found) ,困扰很久,网上也分析了很多原因及对应的解决方案。出现这个报错根本原因就是系统启动时未加载到mybatis xml映射文件或加载的xml配置文件有错误(比如调用的sql语法、格式错误等,可自行检查)。
我的业务相关的xml映射文件放在了子工程meander-dao下的resource/mybatis/mapper下,而后台管理系统相关的xml映射文件是放在主启动类meander-admin(web项目)的java目录的,之前application.yml中也没用mybatis-plus的相关配置 mapper-locations并未指定xml路径,工程都是正常跑的。但是放到子模块里的xml就是读取不到,经过测试配置mapper-locations:classpath*:mybatis/mapper/**/*.xml,com/meander/**/mapping/*.xml 相关路径后,问题得到了解决。
但是查问题要探究根源,一直困扰我的是:为什么主启动类所在web项目没有手动配置 mapper-locations,却可以正常加载xml呢?
经过debug调试找到了mybatis-plus加载xml的机制。我们在启动服务的时候,有个类:
com.baomidou.mybatisplus.spring.boot.starter.MybatisPlusProperties 会自动从application.yml配置文件读取mapper-locations值(是个数组,如果需要配置多个路径,中间用逗号分隔,分号是不行的)。里面专门有个方法resolveMapperLocations() 用来解析mapper-locations, 代码如下:
public Resource[] resolveMapperLocations() {
ResourcePatternResolver resourceResolver = new PathMatchingResourcePatternResolver();
List<Resource> resources = new ArrayList();
if (this.mapperLocations != null) {
String[] arr$ = this.mapperLocations;
int len$ = arr$.length;
for(int i$ = 0; i$ < len$; ++i$) {
String mapperLocation = arr$[i$];
try {
Resource[] mappers = resourceResolver.getResources(mapperLocation);
resources.addAll(Arrays.asList(mappers));
} catch (IOException var8) {
;
}
}
}
return (Resource[])resources.toArray(new Resource[resources.size()]);
}
在加粗的 if (this.mapperLocations != null) { 这行打上断点后,发现mapperLocations 值是从applicatipon.yml(或application.properties)读取的,当我们没有指定mapperLocations时,系统默认值是:classpath*:**/mapping/*.xml,也就是说会默认从各个子模块的类路径下读取符合“**/mapping/*.xml” 路径的xml文件的。