深入理解 mapper-locations

mybatis-plus.mapper-locations: classpath*:/mapper/**/*.xml 是 MyBatis/MyBatis-Plus 在 Spring Boot 配置文件(如 application.yml 或 application.properties)中的一项关键配置,用于指定 MyBatis Mapper XML 文件的存放路径。以下是详细解释:

1. 配置含义

mybatis-plus:

mapper-locations: classpath*:/mapper/**/*.xml

作用:告诉 MyBatis/MyBatis-Plus 去哪里扫描并加载 SQL 映射文件(即 *Mapper.xml或者 *Dao.xml文件)。

值解析:

classpath*::从所有类路径(包括依赖的 JAR 文件)中搜索。

/mapper/**/*.xml:匹配 resources/mapper/ 目录及其子目录下的所有 .xml 文件。

2. 为什么需要这个配置?

默认行为:

MyBatis 默认会尝试加载与 Mapper 接口同名的 XML 文件(如 UserDao.java 对应 UserDao.xml),但需要明确指定 XML 的存放路径。

灵活定位:

如果你的 XML 文件不放在默认位置(如 resources/com/example/dao/),需要通过此配置自定义路径。

3. 常见配置示例

(1) 多路径匹配

mybatis-plus:

mapper-locations:

- classpath*:/mapper/**/*.xml

- classpath*:/com/example/custom/**/*.xml

支持多个路径,用列表形式表示。

(2) 不同项目结构

如果 XML 文件直接放在 resources/mapper/ 下:

mybatis-plus:

mapper-locations: classpath*:mapper/*.xml

如果 XML 文件按模块分包:

mybatis-plus:

mapper-locations: classpath*:com/example/**/dao/*.xml

4. 与 @MapperScan 的关系

mapper-locations:告诉 MyBatis XML 文件在哪里。

@MapperScan:告诉 Spring Mapper 接口在哪里(扫描 DAO 接口)。

两者需配合使用,例如:

@SpringBootApplication

@MapperScan("com.example.dao") // 扫描接口

public class App {}

mybatis-plus:

mapper-locations: classpath*:com/example/dao/*.xml # 扫描 XML

5. 注意事项

路径通配符:

**:匹配多级目录(如 mapper/user/UserMapper.xml)。

*:匹配单级目录或文件名(如 mapper/*.xml)。

文件命名:

XML 文件名通常与 Mapper 接口名一致(如 UserMapper.java 对应 UserMapper.xml)。

优先级:

如果同时存在注解(如 @Select)和 XML,XML 优先级更高。

资源过滤:

确保 Maven 将 XML 文件复制到 target/classes 或构建输出目录。

6. 如何验证配置生效?

检查日志:

启动时查看 MyBatis 日志,是否加载了预期的 XML 文件:

[MyBatis] Mapped SQL statement: com.example.dao.UserMapper.selectById

解压 JAR 检查:

打包后解压 JAR,确认 XML 文件在指定路径下(如 BOOT-INF/classes/mapper/UserMapper.xml)。

故意写错路径:

修改为一个不存在的路径(如 classpath*:/nonexist/**/*.xml),如果启动时报 BindingException,说明原配置已生效。