记录生活中的点点滴滴

0%

Could not find resource com/xxx/xxxMapper.xml

前言:

​ mybatis错误——java.io.IOException: Could not find resource com/xxx/xxxMapper.xml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
  Exception in thread "main" java.lang.RuntimeException: org.apache.ibatis.builder.BuilderException: Error parsing SQL Mapper Configuration. Cause: java.io.IOException: Could not find resource com/mybatis/mapper/StudentMapper.xml
at com.mybatis.util.MyBatisSqlSessionFactory.getSqlSessionFactory(MyBatisSqlSessionFactory.java:33)
at com.mybatis.util.MyBatisSqlSessionFactory.main(MyBatisSqlSessionFactory.java:44)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:147)
Caused by: org.apache.ibatis.builder.BuilderException: Error parsing SQL Mapper Configuration. Cause: java.io.IOException: Could not find resource com/mybatis/mapper/StudentMapper.xml
at org.apache.ibatis.builder.xml.XMLConfigBuilder.parseConfiguration(XMLConfigBuilder.java:106)
at org.apache.ibatis.builder.xml.XMLConfigBuilder.parse(XMLConfigBuilder.java:89)
at org.apache.ibatis.session.SqlSessionFactoryBuilder.build(SqlSessionFactoryBuilder.java:77)
at org.apache.ibatis.session.SqlSessionFactoryBuilder.build(SqlSessionFactoryBuilder.java:63)
at com.mybatis.util.MyBatisSqlSessionFactory.getSqlSessionFactory(MyBatisSqlSessionFactory.java:31)
... 6 more
Caused by: java.io.IOException: Could not find resource com/mybatis/mapper/StudentMapper.xml
at org.apache.ibatis.io.Resources.getResourceAsStream(Resources.java:108)
at org.apache.ibatis.io.Resources.getResourceAsStream(Resources.java:95)
at org.apache.ibatis.builder.xml.XMLConfigBuilder.mapperElement(XMLConfigBuilder.java:315)
at org.apache.ibatis.builder.xml.XMLConfigBuilder.parseConfiguration(XMLConfigBuilder.java:104)
... 10 more

最终通过上网查找找到了三种解决方案,现在整理总结!希望可以帮助到其他人!
在说解决方案之前,先申明我的环境!我会用的开发工具是IDEA ,项目构建使用Maven!网上一些教程使用的Eclipse开发工具,项目是普通的java web项目,所以开发工具和构建项目不同就会存在一些出入(坑)!

我项目的目录和xxxMapper.xml的位置如下图:

原因:IDEA是不会编译src的java目录的xml文件,所以在Mybatis的配置文件中找不到xml文件!(也有可能是Maven构建项目的问题,网上教程很多项目是普通的Java web项目,所以可以放到src下面也能读取到

解决方案1:

不将xml放到src目录下面,将xxxMapper.xml放到Maven构建的resource目录下面!

解决方案2:

1
2
3
4
5
6
7
8
9
10
<build>
<resources>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.xml</include>
</includes>
</resource>
</resources>
</build>

解决方案2,参考资料:mybatis 找不到映射器xml文件

解决方案3:

我测试时候只有 mapper resource 这种方式加载不到资源,其他的url class和package都可以,如果想解决问题的话,可以不使用resource这种方式!