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