MyBatis启动报错:无法找到Student.xml资源,求解决方案
解决MyBatis找不到Student.xml资源的问题
核心排查与修复步骤
1. 修正Mapper路径配置
在SqlMapConfig.xml的<mappers>节点中,移除resource路径开头的斜杠,修改为:
<mappers> <mapper resource="com/example/demoMyBatis/XML/Student.xml" /> </mappers>
MyBatis的resource属性基于classpath根目录解析,开头的斜杠会导致路径匹配异常,去掉后才能正确定位编译后的文件。
2. 验证编译后的文件位置
执行mvn clean package重新编译项目,检查target/classes/com/example/demoMyBatis/XML/目录下是否存在Student.xml:
- 如果不存在,说明Maven资源过滤配置未生效:
- 将pom.xml中
<resource>节点的filtering改为false(过滤可能破坏XML文件结构):<resource> <directory>src/main/java</directory> <includes> <include>**/*.properties</include> <include>**/*.xml</include> </includes> <filtering>false</filtering> </resource> - 重新执行
mvn clean compile,再次检查target目录。
- 将pom.xml中
3. 确认文件实际存放路径
确保Student.xml确实放在src/main/java/com/example/demoMyBatis/XML/目录下(与Student.java同目录)。如果放在src/main/resources下,需调整为src/main/resources/com/example/demoMyBatis/XML/Student.xml,此时SqlMapConfig中的路径保持不变即可。
Spring Boot整合MyBatis的优化建议(可选)
既然使用mybatis-spring-boot-starter,建议放弃传统的SqlMapConfig.xml,改用Spring Boot自动配置简化开发:
- 删除
SqlMapConfig.xml,在src/main/resources下创建application.properties:
# MyBatis配置 mybatis.type-aliases-package=com.example.demoMyBatis.XML mybatis.mapper-locations=classpath:com/example/demoMyBatis/XML/*.xml # 数据源配置 spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver spring.datasource.url=jdbc:mysql://localhost:3306/mybatis?useSSL=false&serverTimezone=UTC spring.datasource.username=root spring.datasource.password=12345678
注意:驱动类改用com.mysql.cj.jdbc.Driver,适配MySQL 8.0+版本,原com.mysql.jdbc.Driver已废弃。
- 在Spring Boot启动类上添加
@MapperScan注解扫描Mapper接口:
@SpringBootApplication @MapperScan("com.example.demoMyBatis.XML") public class DemoMyBatisXmlApplication { public static void main(String[] args) { SpringApplication.run(DemoMyBatisXmlApplication.class, args); } }
内容的提问来源于stack exchange,提问作者Trung Đức Lệ
相关产品推荐
相关产品推荐

