SpringBoot+AOP+MybatisPlus实现多数据源动态切换遇到关于sqlSessionFactoryBean的坑

网上数据源动态切换的文章大多千篇一律而且还是各种地方都有坑,博主在这里被坑惨了。。。

多数据源动态切换需要自定义实例化sqlSessionFactoryBean
然后自定义的需要手动设置setMapperLocations、setTypeAliasesPackage不然执行sql时会报
org.apache.ibatis.binding.BindingException:
* Invalid bound statement (not found)…
原因以及解决方案如下:

@Bean
    @ConfigurationProperties(prefix = "mybatis")
    public MybatisSqlSessionFactoryBean sqlSessionFactoryBean() {
        MybatisSqlSessionFactoryBean sqlSessionFactoryBean = new MybatisSqlSessionFactoryBean();
        /**
         * 这里在applications.properties里面配置了
         * mybatis-plus.type-aliases-package=com.jwt.springboot.dao
         * mybatis-plus.mapper-locations=classpath:mapper/*Mapper.xml
         * 但多数据源情况下执行sql总会报:org.apache.ibatis.binding.BindingException:
         * Invalid bound statement (not found)........
         * 原因是 this.mapperLocations 为null
         *
         * 注!!!!这里有大坑, 因为这里是自定义的sqlSessionFactoryBean,所以导致
         * 没有启动时没有通过org.mybatis.spring.boot.autoconfigure.MybatisPlusAutoConfiguration
         * 类的sqlSessionFactory(DataSource dataSource)方法自动装配sqlSessionFactoryBean
         * 自定义的sqlSessionFactoryBean所以也没设置mapperLocations
         * 故自定义实例化sqlSessionFactoryBean这里需要手动设置mapperLocations
         * 可参考:https://developer.aliyun.com/article/754124
         */
        if (!ObjectUtils.isEmpty(this.mybatisPlusProperties.resolveMapperLocations())) {
            sqlSessionFactoryBean.setMapperLocations(this.mybatisPlusProperties.resolveMapperLocations());
        }
        if (this.mybatisPlusProperties.getTypeAliasesPackage() != null) {
            sqlSessionFactoryBean.setTypeAliasesPackage(this.mybatisPlusProperties.getTypeAliasesPackage());
        }
        sqlSessionFactoryBean.setDataSource(dynamicDataSource());
        return sqlSessionFactoryBean;
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值