青衣画白扇 2020-08-10 10:03 采纳率: 25%
浏览 343
已采纳

springboot +mybatisplus 中如何更换默认的数据源(不是aop的那种线程切换)

@Bean
    public SqlSessionFactory sqlSessionFactory() throws Exception {
     MybatisSqlSessionFactoryBean sqlSessionFactoryBean = new MybatisSqlSessionFactoryBean();
        sqlSessionFactoryBean.setDataSource(dynamicDataSource());
        sqlSessionFactoryBean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath*:com/jksd/mapper/*.xml"));
        sqlSessionFactoryBean.setTypeAliasesPackage("com.jksd.model");
      //导入mybatis配置
        MybatisConfiguration configuration = new MybatisConfiguration();
        configuration.setJdbcTypeForNull(JdbcType.NULL);
        configuration.setMapUnderscoreToCamelCase(true);
        configuration.setCacheEnabled(false);
        sqlSessionFactoryBean.setConfiguration(configuration);
        //PerformanceInterceptor(),OptimisticLockerInterceptor()
        //导入全局配置
        //解决驼峰命名失效
       // sqlSessionFactoryBean.setConfiguration(configuration());
        return sqlSessionFactoryBean.getObject();
    } 
//修改MyBatis的数据源
            MybatisSqlSessionFactoryBean SqlSessionFactory = (MybatisSqlSessionFactoryBean) SpringContextUtils.getBean(MybatisSqlSessionFactoryBean.class);
          Environment environment =SqlSessionFactory.getObject().getConfiguration().getEnvironment();
          Field dataSourceField = environment.getClass().getDeclaredField("dataSource");
          dataSourceField.setAccessible(true);//跳过检查
          dataSourceField.set(environment,datasourceId);//修改mybatis的数据源

报错
org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.baomidou.mybatisplus.extension.spring.MybatisSqlSessionFactoryBean' available

有没有大佬用过啊 (想实现的就是 切换数据源后所有 关于数据库的操作都是切换过去的不是 aop那种线程中切换使用)

  • 写回答

1条回答 默认 最新

  • dabocaiqq 2020-08-10 14:44
    关注
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

问题事件

  • 已采纳回答 2月22日

悬赏问题

  • ¥20 idea运行测试代码报错问题
  • ¥15 网络监控:网络故障告警通知
  • ¥15 django项目运行报编码错误
  • ¥15 请问这个是什么意思?
  • ¥15 STM32驱动继电器
  • ¥15 Windows server update services
  • ¥15 关于#c语言#的问题:我现在在做一个墨水屏设计,2.9英寸的小屏怎么换4.2英寸大屏
  • ¥15 模糊pid与pid仿真结果几乎一样
  • ¥15 java的GUI的运用
  • ¥15 我想付费需要AKM公司DSP开发资料及相关开发。