自定义 MP 的 mapper 方法绑定 xml 文件报错:Invalid bound statement (not found)
spring boot 版本:v2.7.8
Mybatis-plus 版本:v3.5.3.1
mapper 方法绑定 xml 文件报错:Invalid bound statement (not found)
报错是因为没有把 Mapper 自定义的方法和 xml 文件中定义的 sql 关联起来。
检查 namespace、id 和 resultType,可以直接跳转到对应的类,都没有问题。
imooc 视频教程 中使用的是 eclipse,但并没有出现问题。 教程中在 yml 中添加了 mapper 的位置:
mybatis-plus:
mapper-locations:
- com/mp/mapper/*.xml这个我有配置,但执行还是会报错:Invalid bound statement (not found)。
视频下有一个问答里提到可以修改 mapper 的位置:
mybatis-plus:
mapper-locations:
- classpath:mapper/*.xml复制一份 mapper 到 resources 目录下,测试是可以的。实际上,只要在 resources 目录下,即便把 mybatis-plus.mapper-locations 配置项注释掉也是可以正常绑定的。
也就是说,mapper 的 xml 文件直接放在 resources 文件夹下是可以直接使用的。检查一些已有的 springboot 项目,实际情况也印证了这一点。
问答及后续百度的教程里,提到了一种在 pom.xml 文件中配置 resources, 使 xml 文件能够被识别:
<build>
<resources>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.xml</include>
</includes>
</resource>
</resources>
...注意:修改 pom.xml 文件之后需要重载 Maven 项目使其生效。
然后就报错了:Failed to load ApplicationContext...Failed to determine a suitable driver class。
百度了多个教程,里面的情况跟当前都不一致。target -> classes 下并没有发现 properties 和 yml 等项目配置文件,突然意识到好像没有引入 resources 下的项目配置文件,有可能这样定义之后默认的资源配置就失效了,需要我们在配置的时候把默认的 resources 文件夹和下面的配置文件加入到其中:
<build>
<resources>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.xml</include>
</includes>
<filtering>false</filtering>
</resource>
<resource>
<directory>src/main/resources</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.yml</include>
<include>**/*.xml</include>
</includes>
<filtering>false</filtering>
</resource>
</resources>
...这样,在代码包和资源包下都可以识别 xml 文件。测试发现依然是 Invalid bound statement (not found) 错误。这好像回到了原点,再次检查 yml 文件时突然发现,之前测试是把 mybatis-plus.mapper-locations 配置项注释了。打开注释,再次测试,成功!
完整版的配置:
application.yml :
mybatis-plus:
mapper-locations:
- com/mp/mapper/*.xml
- classpath:mapper/*.xmlpom.xml :
<build>
<resources>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.xml</include>
</includes>
<filtering>false</filtering>
</resource>
<resource>
<directory>src/main/resources</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.yml</include>
<include>**/*.xml</include>
</includes>
<filtering>false</filtering>
</resource>
</resources>
...注意:filtering 在这里没有起作用,这样配置的 resources 相当于是开了一个白名单,include 进来的是允许访问的资源文件。如果后续想要访问一些其他的静态资源文件,如 html、js、css、jpg 等,就需要手动添加。
综上,最好还是将 mapper 的 xml 文件放在默认的 resources 资源文件夹下。这样可以直接访问,无需任何配置。
中间有 maven 更新报错 cannot reconnect,关闭项目重新打开问题就消失了。
本作品采用 知识共享署名-相同方式共享 4.0 国际许可协议 进行许可。
海滨擎蟹
微信
支付宝