[SpringBoot][Mybatis]springboot整合mybatis扫描不到Mapper.xml解决方案

在SpringBoot整合MyBatis时,可能会出现扫描不到Mapper.xml文件的问题

常见的报错是:

  org.apache.ibatis.binding.BindingException: Invalid bound statement (not found):接口方法的全限定名

一般出现这种错误,都是映射不到mapper.xml文件的问题:

排查方向:

  1.mapper接口和对应的xml文件路径是否在同一个目录下?

  比如说:  mapper接口全限定名:  com.xxx.mybatis.mapper.xxxMapper

  那对应的xxxMapper.xml,是同样的在java目录下com.xxx.mybatis.mapper包下,如图:

  

此时:

  有一个隐藏的问题:  maven项目运行时会打包,而java目录下的xml资源在打包时会被忽略.

解决方案:

  在pom.xml中配置如下:

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

  2.如果不是在同一目录下,而是xml文件是在resources目录下,那要查看mapper接口和xml文件是否对应?

  

  上图中就是相对应的,此时是可以扫描到的

如果不对应,还可以通过自定义扫描路径的方式:

  在application.properties中,配置如下:

mybatis.mapper-locations=classpath:想要扫描的路径,如com/xxx/mybatis/*.xml

到此:问题应该就可以解决了

有些小伙伴可能是从ssm转过来的,很好奇以前配置的SqlSessionFactor和MapperScan都没了,是不需要了吗

了解一下SpringBoot的自动装配原理,这里就不多赘述了.

mybatis-spring-boot-starter也提供了对应的自动装配类

猜你喜欢

转载自www.cnblogs.com/nysd/p/12745110.html