MyBatis:解决找不到绑定的mapper问题,org.apache.ibatis.binding.BindingException: Invalid bound statement (not found)

产生原因

默认情况下,MyBatis会去接口文件所在的目录寻找xml文件。当xml文件与接口文件目录不在同一目录时,会报错:

org.apache.ibatis.builder.IncompleteElementException: Could not find a parent resultmap with id 'top.testops.mall.mbg.mapper.CheckGroupMapper'
	at org.apache.ibatis.builder.MapperBuilderAssistant.addResultMap(MapperBuilderAssistant.java:188) ~[mybatis-3.5.7.jar:3.5.7]
	at org.apache.ibatis.builder.ResultMapResolver.resolve(ResultMapResolver.java:47) ~[mybatis-3.5.7.jar:3.5.7]
	at org.apache.ibatis.session.Configuration.parsePendingResultMaps(Configuration.java:909) ~[mybatis-3.5.7.jar:3.5.7]
	at org.apache.ibatis.session.Configuration.buildAllStatements(Configuration.java:873) ~[mybatis-3.5.7.jar:3.5.7]
	at com.baomidou.mybatisplus.core.MybatisConfiguration.hasStatement(MybatisConfiguration.java:303) ~[mybatis-plus-core-3.4.3.4.jar:3.4.3.4]
	at org.apache.ibatis.session.Configuration.hasStatement(Configuration.java:853) ~[mybatis-3.5.7.jar:3.5.7]
	at org.apache.ibatis.binding.MapperMethod$SqlCommand.resolveMappedStatement(MapperMethod.java:257) ~[mybatis-3.5.7.jar:3.5.7]

解决方案

方法一:

把接口文件与xml文件放在同一目录

方法二

application.yml文件配置mapper-locations,即:

mybatis-plus:
  mapper-locations: classpath:top/testops/**/*.xml

注意一:
此处的配置,不是classpath:path/to/mappers/*.xml,而是classpath:com/my/package/persistence/*.xml。即:不是xml文件的路径,而是包名对应的目录(如:src/main/java/example/mapper/.xml),而是Java中的包名(如:top/testops/mapper/.xml,xml所在的包名为:top.testops.mapper)

注意二:
当mapper不是放在resources目录时,xml文件不会编译到target文件夹。需要在pom.xml文件中添加配置:

    <build>
        <resources>
            <!-- 编译 src/main/java 目录下的 mapper 文件 -->
            <resource>
                <directory>src/main/java</directory>
                <includes>
                    <include>**/*.xml</include>
                </includes>
                <filtering>false</filtering>
            </resource>
        </resources>
    </build>
posted @ 2021-10-08 10:18  Feng1024  阅读(1170)  评论(0编辑  收藏  举报