关于 MyBatis 找不到映射文件的问题
IDEA 环 境 maven 项 目 中 , MyBatis 的 映 射 文 件 默 认 放 在 资 源 目 录 resources
(src/main/resources)下,在 mybatis-config.xml 中的<mappers>中定义<mapper>元素,指定
resources 属性为资源目录(resources)下的某个子目录(如 mapper)下的文件,一般格式
为:
<mappers>
<mapper resource="mapper/UserMapper.xml" />
</mappers>
习 惯 上 , 会 把 映 射 文 件 放 在 源 代 码 目 录 的 某 个 包 ( 在 src/main/java 下 建 立 的 一 个 包
com.wfu.mapper),这时候,如果在核心配置文件中进行如下配置,
<mappers>
<mapper resource="com/wfu/mapper/UserMapper.xml" />
</mappers>
就 会出 现 IO 异 常 , 提 示 找 不 到 文 件 , 错 误 提 示 为 : java.io.IOException: Could not find resource
com/itheima/mapper/StudentMapper.xml。
解决方法:
在 maven 配置文件 pom.xml 中,指定资源目录,具体如下
<build>
<resources>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
<filtering>true</filtering>
</resource>
</resources>
</build>
注:Idea 中新建 maven 项目不会自动生成这段配置,需要自己添加。
然后,如果该错误还存在,需要点击 maven 悬浮窗,执行 Load maven changes。
注意,此时,如果映射文件中有中文,可能会提示“2 字节的 UTF-8 序列的字节 2 无效”,例如:
Error parsing SQL Mapper Configuration. Cause: org.apache.ibatis.builder.BuilderException: Error creating
document instance. Cause: com.sun.org.apache.xerces.internal.impl.io.MalformedByteSequenceException:
2 字节的 UTF-8 序列的字节 2 无效。
解决方法:将映射文件首行的编码字符集由“UTF-8”,改为“UTF8”或者“GBK”。
评论0
最新资源