Fork me on Gitee

SpringBoot整合Mybatis-Plus报错org.apache.ibatis.binding.BindingException

SpringBoot整合Mybatis-Plus报错org.apache.ibatis.binding.BindingException

Mapper接口,被Spring注入后,却无法正常的使用mapper.xml的sql;你的接口已经成功的被扫描到,但是当Spring尝试注入一个代理(MyBatista实现)的实现类后,却无法正常使用。这里的可能发生的情况有如下几种;

接口已经被扫描到,但是代理对象没有找到,即使尝试注入,也是注入一个错误的对象(可能就是null)
接口已经被扫描到,代理对象找到了,也注入到接口上了,但是调用某个具体方法时,却无法使用(可能别的方法是正常的)

排查方法:

  • 网上一搜博客很多,说的也是大同小异,最重要的一点就是检查配置,肯定是配置弄错了,从头到尾的细心检查。

  • mapper接口和mapper.xml是否在同一个包(package)下?名字是否一样(仅后缀不同)?

    比如,接口名是NameMapper.java;
    对应的xml就应该是NameMapper.xml
    
  • mapper.xml的命名空间(namespace)是否跟mapper接口的包名一致?

    比如,你接口的包名是com.abc.dao,接口名是NameMapper.java,
    那么你的mapper.xml的namespace应该是com.abc.dao.NameMapper
    
    <mapper namespace="com.cn.routine.mapper.UserMapper">
    
  • 接口的方法名,与xml中的一条sql标签的id一致

    比如,接口的方法List<User> findAll();
    那么,对应的xml里面一定有一条是<select id="findAll" resultMap="**">****</select>
    
  • 如果接口中的返回值List集合(不知道其他集合也是),那么xml里面的配置,尽量用resultMap(保证resultMap配置正确),不要用resultType

  • 如果你的项目是maven项目,请你在编译后,到接口所在目录看一看,很有可能是没有生产对应的xml文件,因为maven默认是不编译的,因此,你需要在你的pom.xml的里面,加这么一段,mapper.xml没有按照传统的maven架构进行放置

    <build>
            <resources>
                <resource>
                    <directory>src/main/java</directory>
                    <includes>
                        <include>**/*.xml</include>
                        <include>**/*.properties</include>
                    </includes>
                    <filtering>true</filtering>
                </resource>
                <resource>
                    <directory>src/main/resources</directory>
                    <includes>
                        <include>**/*.xml</include>
                        <include>**/*.properties</include>
                    </includes>
                    <filtering>true</filtering>
                </resource>
            </resources>
        </build>
    
  • 随意在xml文件中加一个空格或者空行然后保存。

  • 检查配置文件(yml文件)具体的字母有没有写错。

  • 启动类的扫描路径是Mapper的路径,少写包名能扫描到但是会报错。

    @MapperScan("com.cn.routine.mapper")
    public class RoutineApplication {
        public static void main(String[] args) {
            SpringApplication.run(RoutineApplication.class, args);
        }
    }
    
    错误包名:@MapperScan("com.cn.routine")
    

参考文章

posted @ 2021-06-21 17:38  明叶师兄。  阅读(569)  评论(0编辑  收藏  举报