1. 问题背景与现象描述
最近接手了一个基于Spring Boot的遗留项目框架,需要在该框架中集成Quartz定时任务模块。在开发过程中遇到了一个典型的MyBatis Mapper扫描问题:虽然通过@MapperScan注解能够扫描到Quartz模块中的Mapper接口类,但在实际调用时却抛出"Invalid bound statement"异常,提示找不到对应的SQL映射。
具体现象表现为:
- 在启动类上添加
@MapperScan(value = {"com.xx.quartz.mapper"})后,通过Spring容器检查确认Mapper接口已被正确加载 - 但执行Mapper方法时抛出
Invalid bound statement (not found): com.xx.quartz.mapper.JobMapper.getCountByJobName异常 - 手动修改Mapper XML文件中的SQL标签(如故意写错select标签),重启应用后不报错,证明XML文件未被加载
- 在application.yml中配置
mybatis-plus.mapper-locations指向XML文件路径后,问题依旧存在
提示:这类问题在微服务架构或多模块项目中尤为常见,特别是在接手他人代码或集成第三方模块时。核心矛盾在于MyBatis的Mapper接口和XML映射文件需要被正确配对加载。
需要模型API调用? 免费领10W Token,多模型网关一键接入 Claude、DeepSeek 等主流模型。
2. 问题排查过程详解
2.1 初步验证XML加载情况
首先通过编程方式验证MyBatis是否加载了目标XML文件。关键排查代码如下:
java复制// 检查已加载的MappedStatement
Configuration config = sqlSessionFactory.getConfiguration();
String statementId = "com.xx.quartz.mapper.JobMapper.getCountByJobName";
Collection<MappedStatement> mappedStatements = config.getMappedStatements();
for (MappedStatement ms : mappedStatements) {
System.out.println("Statement ID: " + ms.getId() + " | XML: " + ms.getResource());
}
if (!config.hasStatement(statementId)) {
System.out.println("❌ MappedStatement not found: " + statementId);
}
这段代码遍历
