mybatis-plus 配置多数据源,无法读取全局配置文件的配置(记一bug)

mybatis-plus 配置多数据源,无法读取全局配置文件的配置

Spring boot + Druid + Mybatis-plus

  • 至于 如何配置多数据源 我就不多说了,网上很多示例自行百度

  • 重点

  • 我用mybatis-plus 配置的多数据源,并且用了它的代码生成器生成了Bean,Mapper,Xml等。生成的时候去掉了表名的前缀

但是在配置文件中指定表名前缀时,并不生效; 配置如下:

mybatis-plus.global-config.db-config.table-prefix=tbl_

执行sql,就会出现表名不存在的错误。

  • 于是就一步步的单点找原因, 现在也不知道是为什么,猜想是和装配多数据源到MybatisSqlSessionFactoryBean里有关系。只是猜想,相关代码如下:
 @Bean("sqlSessionFactory")
    public SqlSessionFactory sqlSessionFactory() throws Exception {
        MybatisSqlSessionFactoryBean sqlSessionFactory = new MybatisSqlSessionFactoryBean();
        sqlSessionFactory.setDataSource(multipleDataSource(getDataSource(),secondaryDataSource()));
        return sqlSessionFactory.getObject();
    }

但是这个不知道如何修改,如有知道的老哥,烦请下面留言。

解决方式

  • 在GlobalConfig 的 DbConfig 里自己set进去,在set到MybatisSqlSessionFactoryBean 里;成功解决!
    如下:
 @Bean("sqlSessionFactory")
    public SqlSessionFactory sqlSessionFactory() throws Exception {
        MybatisSqlSessionFactoryBean sqlSessionFactory = new MybatisSqlSessionFactoryBean();
        sqlSessionFactory.setDataSource(multipleDataSource(getDataSource(),secondaryDataSource()));

        sqlSessionFactory.setGlobalConfig(globalConfig());  //  关键
        return sqlSessionFactory.getObject();
    }
    
    //  自定义配置
    public GlobalConfig globalConfig(){
        GlobalConfig globalConfig = new GlobalConfig();
        GlobalConfig.DbConfig dbConfig = new GlobalConfig.DbConfig();
        dbConfig.setTablePrefix("tbl_");  // 关键
        globalConfig.setDbConfig(dbConfig);
        return globalConfig;
    }

你可能感兴趣的:(java,spring,boot,mybatis-plus)