MyBatis 找不到 mapper.xml 的主因是路径错误或资源未被 Maven 打包;需检查 target/classes 中是否存在对应 XML、pom.xml 是否配置 resources、mybatis.mapper-locations 是否正确使用 classpath 前缀、namespace 是否与接口全限定名严格一致。

MyBatis 找不到 mapper.xml 文件的常见原因
不是路径写错了,就是资源没被 Maven 打包进去——这两类问题占了 90% 以上。Spring Boot 默认只扫描 src/main/resources 下的文件,而很多人把 mapper.xml 放在 src/main/java/com/example/mapper/ 里,和 Mapper.java 同目录,结果编译后 XML 根本不进 target/classes。
- 检查
target/classes目录下是否存在对应 XML 文件(比如com/example/mapper/UserMapper.xml),没有就说明没打包进去 - Maven 默认不处理
src/main/java下的非.java文件,必须在pom.xml中显式配置<resources> - 路径区分大小写,
UserMapper.xml和usermapper.xml在 Linux 上是两个文件
mybatis.mapper-locations 配置写法与生效条件
这个配置只在 Spring Boot 环境下有效,且仅当 MyBatis 没通过 @MapperScan 自动注册接口时才真正起作用;一旦用了 @MapperScan,它基本被忽略——很多人调了半天配置,其实压根没走这条路。
- 正确写法是用 classpath 前缀:
classpath:mapper/*.xml或classpath*:mapper/**/*.xml(后者支持多 module) - 不要写成文件系统路径:
file:/xxx/mapper/,Spring Boot 默认不启用file:协议加载资源 - 如果 XML 在 jar 包里(比如依赖了另一个模块),必须用
classpath*:,单个classpath:只查第一个匹配项 - 配置项名是
mybatis.mapper-locations,不是mybatis.config-location或mapper-locations
XML 文件命名与 namespace 必须严格匹配接口
MyBatis 不靠文件路径绑定接口,而是靠 <mapper namespace="com.example.mapper.UserMapper"> 这个字符串和接口全限定名是否一致。哪怕路径完全正确,namespace 写错一个字母,也会报 Invalid bound statement (not found)。
- 确保
namespace值 = 对应Mapper接口的完整类名,不能是实现类、不能漏包名、不能拼错 - 接口名和 XML 文件名可以不同(如
UserDao.java+UserMapper.xml),但 namespace 必须指向接口 - IDE(如 IntelliJ)有时会自动补全错误的 namespace,尤其在复制粘贴后没改干净
- 用
MapperScannerConfigurer或@MapperScan时,namespace 错误会导致接口根本没注册进 SqlSessionTemplate
Maven 多模块下 XML 资源未被子模块继承
父模块写了 <resources>,子模块没重写,就会沿用 Maven 默认规则——跳过 src/main/java 下所有非 Java 文件。这是企业项目中最隐蔽的坑。
- 每个含 mapper.xml 的子模块
pom.xml都要单独配<build><resources>,不能只靠父 POM - 推荐写法:
<resource> <directory>src/main/java</directory> <includes><include>**/*.xml</include></includes> </resource>
- 打包后打开 jar,直接搜索
.xml,确认它真在 classpath 下对应位置 - 如果用了
spring-boot-maven-plugin的repackage,注意它不会改变资源打包逻辑,该漏还是漏
BindingException。调试时盯死 target/classes 目录结构和日志里实际加载的 resource URL,比反复改配置有用得多。










