问题描述:
使用mybatis时这个错是一个很常见的错误了,这个报错也很明显就是找不到某某的mapper.xml文件,首先我们应该清楚mapper.xml文件会在我们编译时被加载到(复制一份过去)对应的class路径下,出现这个错的根本原因在于在程序执行时,去对应路径下找这个mapper文件,却找不到,就会报出这个错误,下面是错误详情:
### The error may exist in com/cheng/dao/SupplierMapper.xml ### Cause: org.apache.ibatis.builder.BuilderException: Error parsing SQL Mapper Configuration. Cause: java.io.IOException: Could not find resource com/cheng/dao/SupplierMapper.xml at org.apache.ibatis.exceptions.ExceptionFactory.wrapException(ExceptionFactory.java:30) at org.apache.ibatis.session.SqlSessionFactoryBuilder.build(SqlSessionFactoryBuilder.java:80) at org.apache.ibatis.session.SqlSessionFactoryBuilder.build(SqlSessionFactoryBuilder.java:64) at com.cheng.utils.MybatisUtil.<clinit>(MybatisUtil.java:24) ... 26 more Caused by: org.apache.ibatis.builder.BuilderException: Error parsing SQL Mapper Configuration. Cause: java.io.IOException: Could not find resource com/cheng/dao/SupplierMapper.xml at org.apache.ibatis.builder.xml.XMLConfigBuilder.parseConfiguration(XMLConfigBuilder.java:122) at org.apache.ibatis.builder.xml.XMLConfigBuilder.parse(XMLConfigBuilder.java:99) at org.apache.ibatis.session.SqlSessionFactoryBuilder.build(SqlSessionFactoryBuilder.java:78) ... 28 more Caused by: java.io.IOException: Could not find resource com/cheng/dao/SupplierMapper.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.builder.xml.XMLConfigBuilder.mapperElement(XMLConfigBuilder.java:375) at org.apache.ibatis.builder.xml.XMLConfigBuilder.parseConfiguration(XMLConfigBuilder.java:120) ... 30 more Process finished with exit code -1
问题分析:
问题原因其实已经知道了,就是因为在编译出来的class文件下找不到这个文件,那为什么编译时明明存在,编程成的class文件下却没有呢,其实原因在于maven,maven项目在编译properties与xml等文件时有时可能并不会将它们编译到对应的class路径里面,这时就需要我们手动指定将这些文件导出到class文件目录下。
问题解决:
在pom.xml中添加以下内容,告诉maven将xml、properties等文件导出到class文件目录下,问题解决,需要说的是若是父子工程,则只需要在父工程中添加如下配置即可(plugin中配置的jdk版本请忽略)。
<build> <plugins> <!--指定当前工程jdk的版本--> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <configuration> <source>1.8</source> <target>1.8</target> </configuration> </plugin> </plugins> <resources> <!--导出静态资源文件,防止xml配置文件未加载--> <resource> <directory>src/main/java</directory> <includes> <include>**/*.properties</include> <include>**/*.xml</include> </includes> <filtering>true</filtering> </resource> <resource> <directory>src/main/resources</directory> <includes> <include>**/*.properties</include> <include>**/*.xml</include> </includes> <filtering>true</filtering> </resource> </resources> </build>