Mybatis报错:Could not find resource mybatis-conf.xml
报错截图:
报错内容:
java.io.IOException: Could not find resource mybatis-conf.xml
at org.apache.ibatis.io.Resources.getResourceAsStream(Resources.java:114)
at org.apache.ibatis.io.Resources.getResourceAsStream(Resources.java:100)
at org.apache.ibatis.io.Resources.getResourceAsReader(Resources.java:160)
at MybatisAdvancedTest.testQueryByNo(MybatisAdvancedTest.java:23)
CSDN上jeanFlower在文章说这是IDEA默认不编译src目录下的xml文件造成的(在后面也贴出他的解决办法),而我的mybatis-config.xml文件时在resources目录下,Debug进去观看流程发现Resources.getResourceAsReader根本没有加载到这个xml配置文件.
代码示意:
// 根据学号查询一个学生
@Test
public void testQueryByNo() throws IOException {
String resource = "mybatis-conf.xml";
Reader reader = Resources.getResourceAsReader(resource);
SqlSessionFactory sessionFactory
= new SqlSessionFactoryBuilder().build(reader);
SqlSession session = sessionFactory.openSession();
//传入StudentMapper接口,返回该接口的mapper代理对象studentMapper
StudentMapper studentMapper = session.getMapper(StudentMapper.class);//接口
//通过mapper代理对象studentMapper,来调用IStudentMapper接口中的方法
Student student = studentMapper.queryStudentByNo(1);
System.out.println(student+"****");
session.close();
}
解决办法:
将上面的Test方法中这部分代码进行替换:
String resource = "mybatis-conf.xml";
Reader reader = Resources.getResourceAsReader(resource);
替换成:
Reader reader = Resources.getResourceAsReader("mybatis-conf.xml");
原因暂时未知,明天Debug更新
如果是xml未被idea正常编译的问题,例如IDEA开发,但是没有将mybatis-config.xml放在resources目录下,例如放在src/main/java下,那么在pom.xml末尾添加build代码,告诉idea对我们的配置文件进行编译:
解决方案二
<build>
<resources>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.xml</include>
</includes>
</resource>
</resources>
</build>
解决方案三
将配置文件移到resources目录下,rebuild我们的项目.