在确保其他配置都正确的情况下,检查打包时有没有将Mapper.xml
一起打包进来。如果你是把Mapper.xml
文件和Mapper
类放在一起,或者是通过Mybatis
逆向工程生成而直接拷贝的文件,很容易出现org.apache.ibatis.binding.BindingException: Invalid bound statement (not found)
异常,原因是Maven编译时没有把**Mapper.xml
文件编译进来,在pom.xml
中或者在父工程的pox.xml
中添加:
<build>
<resources>
<!--编译之后包含xml-->
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.xml</include>
</includes>
<filtering>true</filtering>
</resource>
</resources>
</build>
或者:
<build>
<!--
此plugin可以用
利用此plugin,把源代码中的xml文件,
打包到相应位置,这里主要是为了打包Mybatis的mapper.xml文件
-->
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>build-helper-maven-plugin</artifactId>
<version>1.8</version>
<executions>
<execution>
<id>add-resource</id>
<phase>generate-resources</phase>
<goals>
<goal>add-resource</goal>
</goals>
<configuration>
<resources>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.xml</include>
</includes>
</resource>
</resources>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
更或者是在resource资源目录下建立一个mapper文件夹用来存放mapper.xml配置文件,然后在sqlMapConfig.xml
配置文件中批量加载mapper配置文件
<mappers>
<mapper resource="mybatis/mapper/*.xml"/>
</mappers>
或是spring配置文件中批量加载mapper
<!--自动加载所有的mapper.xml文件,不再需要单独配置 -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="configLocation" value="classpath:spring/sqlMapConfig.xml"/>
<property name="mapperLocations">
<!-- 批量扫描maven resource资源目录下的mapper配置文件-->
<value>classpath:mybatis/mapper/*.xml</value>
</property>
</bean>