springboot mybatis 多数据源配置支持切换以及一些坑


一 添加每个数据源的config配置,单个直接默认,多个需要显示写出来

@Configuration
@MapperScan(basePackages ="com.zhuzher.*.mapper", sqlSessionTemplateRef  = "crmSqlSessionTemplate")
public class CrmDataSourceConfig {
    @Bean(name = "crmData")
    @ConfigurationProperties(prefix = "spring.datasource.crm") // application.properteis中对应属性的前缀
    @Primary
    public DataSource crmDataSourceConfig() {
        return DataSourceBuilder.create().build();
    }


    @Bean(name = "crmSqlSessionFactory")
    @Primary
    public SqlSessionFactory crmSqlSessionFactory() throws Exception {
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        bean.setDataSource(crmDataSourceConfig());
        //这段代码必须要,否则不会识别xml
        bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:mappings/*.xml"));
        return bean.getObject();
    }

    @Bean(name = "crmSqlSessionTemplate")
    @Primary
    public SqlSessionTemplate crmSqlSessionTemplate() throws Exception {
        return new SqlSessionTemplate(crmSqlSessionFactory());
    }
}
@Primary 表示默认的,必须且指定一个,mapper位置也要对应放在不同位置,利用不同的mapper请求不同的数据源数据
二 属性文件配置多个数据源,对应config文件中前缀

 

 

三 接口引用不同mapper请求不同数据源数据

四 坑

1 url需要使用jdbc-url

2 xml位置需要在每个config显示置顶位置

3 一定要指定一个默认的数据源,用注解

@Primary


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM