mybatis配置错误解决方法:
我们在配置mybatis的时候经常会出现的错误,通常解决方案有三种。主要造成的原因是:IDEA是不会编译src的java目录的xml文件,所以在Mybatis的配置文件中找不到xml文件!(也有可能是Maven构建项目的问题,网上教程很多项目是普通的Java web项目,所以可以放到src下面也能读取到)
问题描述:
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原因分析:
IDEA是不会编译src的java目录的xml文件,所以在Mybatis的配置文件中找不到xml文件!(也有可能是Maven构建项目的问题,网上教程很多项目是普通的Java web项目,所以可以放到src下面也能读取到)
解决方案1:
不要将xml放到src目录下面,将xxxMapper.xml放到Maven构建的resource目录下(比较常用的方式)!
解决方案2:
不使用resource这种方式加载xml文件或java类!
解决方案3:
在Maven的pom文件中,添加下面代码:
<build>
<resources>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.xml</include>
</includes>
</resource>
</resources>
</build>