我的报错信息是:
org.apache.ibatis.binding.BindingException: Invalid bound statement (not found): com.study.server.mapper.UserMapper.insert
at org.apache.ibatis.binding.MapperMethod$SqlCommand.<init>(MapperMethod.java:227)
at org.apache.ibatis.binding.MapperMethod.<init>(MapperMethod.java:49)
at org.apache.ibatis.binding.MapperProxy.cachedMapperMethod(MapperProxy.java:65)
at org.apache.ibatis.binding.MapperProxy.invoke(MapperProxy.java:58)
at com.sun.proxy.$Proxy88.insert(Unknown Source)
分析
通过跟踪mybatis的源码,发现有两种binding途径,一是配置文件,二是注解。项目中我用的是配置文件,关键代码如下:
public boolean hasStatement(String statementName, boolean validateIncompleteStatements) {
if (validateIncompleteStatements) {
buildAllStatements();
}
return mappedStatements.containsKey(statementName);
}
可以看出有2个会发生该异常的情况
- mappedStatements为{} (跟踪debug发现,我出现这里为空)
- containsKey(statementName),没有找到
mappedStatements为空的原因是由于在spring容器启动时,会解析spring配置文件,这时将去加载资源文件,解析并以key,value的形式缓存在mappedStatements中。而在实际情况下,发现打包时*Mapper.xml并没有自动复制到class输出目录的mapper类包下。从而导致mappedStatements为空。
网上总结的一般原因
Mapper interface和xml文件的定义对应不上,需要检查包名,namespace,函数名称等能否对应上。
按以下步骤一一执行:
1、检查xml文件所在的package名称是否和interface对应的package名称一一对应
2、检查xml文件的namespace是否和xml文件的package名称一一对应
3、检查函数名称能否对应上
4、去掉xml文件中的中文注释
5、随意在xml文件中加一个空格或者空行然后保存
项目中的解决方法:
在使用IDEA开发时,如果打包时*Mapper.xml没有自动复制到class输出目录的mapper类包下,则需要在pom文件中添加mybatis加载配置文件的配置!
如下:
<build>
<resources>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.xml</include>
</includes>
</resource>
<resource>
<directory>src/main/resources</directory>
</resource>
</resources>
</build>
通过在pom文件中添加mybatis加载配置文件,完美解决遇到的问题了。