springboot集成mybatis-plus遇到的巨坑

问题:

1:大家有没有遇到过这样的bug:org.apache.ibatis.binding.BindingException: Invalid bound statement (not found)

 

对没错,小编在集成mybatis-plus的时候,在调用内部集成的insert方法,疯狂报错,调试了很多次,始终解决不了这个问题。

重点:

直接先抛出重点,在集成mybatis-plus的时候,如果使用了sqlSessionFactory,记得在构建的时候一定要使用mybatis-plus加强版的

错误示例:

 @Primary
    @Bean("dbDataSource")
    @ConfigurationProperties(prefix = "spring.datasource.db")
    public DataSource getDbDataSource() {
        return new DruidDataSource();
    }

    @Primary
    @Bean("dbSqlSessionFactory")
    public SqlSessionFactory dbSqlSessionFactory(@Qualifier("dbDataSource") DataSource dataSource) throws Exception {
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        
        bean.setDataSource(dataSource);
        bean.setTypeAliasesPackage(TypeAliasesPackage);
        bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources(MapperLocations));
        return bean.getObject();
    }

    @Primary
    @Bean("dbSqlSessionTemplate")
    public SqlSessionTemplate dbSqlSessionTemplate(@Qualifier("dbSqlSessionFactory") SqlSessionFactory sqlSessionFactory) {
        return new SqlSessionTemplate(sqlSessionFactory);
    }
View Code

这时候的sqlSessionFactory是错误的,无法匹配mybatis-plus所以在使用mybatis-plus公共方法的时候会一直报错

正确示例:

@Primary
    @Bean("dbSqlSessionFactory")
    public SqlSessionFactory dbSqlSessionFactory(@Qualifier("dbDataSource") DataSource dataSource) throws Exception {
        MybatisSqlSessionFactoryBean bean = new MybatisSqlSessionFactoryBean();
        bean.setDataSource(dataSource);
        bean.setTypeAliasesPackage(TypeAliasesPackage);
        bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources(MapperLocations));
        return bean.getObject();
    }

替换为:MybatisSqlSessionFactoryBean 立马解决问题

如果以上没有解决问题那就三步走:

第一:是否配置了

mybatis-plus:
# xml扫描,多个目录用逗号或者分号分隔(告诉 Mapper 所对应的 XML 文件位置)
mapper-locations: classpath*:mapper/*.xml
mybatis:
mapper-locations: classpath*:mapper/*.xml
这两个缺一不可,他们的功能不同,两个地方都必须给添加上。

第二:查看xml中namespece是否填写正确

 

第三:查看resources下的mapper文件是否正确加载到target下的class下面,如果没有配置如下:

  <resources>
            <resource>
                <directory>src/main/java</directory>
                <includes>
                    <include>**/*.xml</include>
                </includes>
                <filtering>false</filtering>
            </resource>
            <resource>
                <directory>src/main/resources</directory>
                <includes>
                    <include>**/*.xml</include>
                    <include>**/*.properties</include>
                    <include>**/*.yml</include>
                </includes>
                <filtering>false</filtering>
            </resource>
        </resources>
View Code

如果都没问题,那就是玄学了。

总结:这篇博客主要就是上面说的构造sqlSessionFactory,这问题很常见,但是大部分都没有讲解到,这里给个总结。

博客贡献:
https://blog.csdn.net/qq_41389354/article/details/112008695

posted @ 2022-07-26 10:58  xzlnuli  阅读(725)  评论(0编辑  收藏  举报