springboot+mybatis/mybatis-plus+druid配置多數(shù)據(jù)源

養(yǎng)成良好的記錄習(xí)慣
作者:黃黃

最近公司業(yè)務(wù)要求查詢(xún)不同數(shù)據(jù)庫(kù)的數(shù)據(jù)組裝在一起,所以需要進(jìn)行多數(shù)據(jù)源配置的操作。

yml添加配置

  • 這里以sqlsever數(shù)據(jù)庫(kù)為例,其他數(shù)據(jù)庫(kù)也類(lèi)似
  • 這里列舉first和second兩個(gè)數(shù)據(jù)源
  datasource:
    first:
      type: com.alibaba.druid.pool.DruidDataSource
      driver-class-name: com.microsoft.sqlserver.jdbc.SQLServerDriver
      jdbc-url: jdbc:sqlserver://192.168.0.001:61592;databaseName=master
      username: xxxxxxx
      password: xxxxxxx
      druid:
        #連接池初始化大小
        initial-size: 5
        #連接池最小值
        min-idle: 5
        #連接池最大值
        max-active: 20
        #最大等待時(shí)間,配置獲取連接等待超時(shí),時(shí)間單位都是毫秒ms
        max-wait: 60000
        #配置間隔多久才進(jìn)行一次檢測(cè),檢測(cè)需要關(guān)閉的空閑連接
        time-between-eviction-runs-millis: 60000
        #配置一個(gè)連接在池中最小生存的時(shí)間
        min-evictable-idle-time-millis: 300000
     
    second:
      type: com.alibaba.druid.pool.DruidDataSource
      driver-class-name: com.microsoft.sqlserver.jdbc.SQLServerDriver
      jdbc-url: jdbc:sqlserver://192.168.0.002:61592;databaseName=master
      username: xxxxxx
      password: xxxxxxxxxxx
      druid:
        #連接池初始化大小
        initial-size: 5
        #連接池最小值
        min-idle: 5
        #連接池最大值
        max-active: 20
        #最大等待時(shí)間,配置獲取連接等待超時(shí),時(shí)間單位都是毫秒ms
        max-wait: 60000
        #配置間隔多久才進(jìn)行一次檢測(cè),檢測(cè)需要關(guān)閉的空閑連接
        time-between-eviction-runs-millis: 60000
        #配置一個(gè)連接在池中最小生存的時(shí)間
        min-evictable-idle-time-millis: 300000

這里列舉幾個(gè)小細(xì)節(jié)

  • driver-class-name不能使用駝峰
  • 一定得使用 jdbc-url,不能使用url

添加數(shù)據(jù)源配置

mybatis對(duì)應(yīng)的配置

first配置

@Configuration
@MapperScan(basePackages = {"com.self.structure.first.dao"}, sqlSessionTemplateRef = "firstSqlSessionTemplate")
public class FirstDruidConfig {
    @Bean(name = "firstDataSource")
    @Primary
    @ConfigurationProperties(prefix = "spring.datasource.first")
    public DataSource firstDataSource() {
        return DataSourceBuilder.create().build();
    }

    @Bean
    public SqlSessionFactory firstSqlSessionFactory(@Qualifier("firstDataSource") DataSource dataSource) throws Exception {
        SqlSessionFactoryBean sqlSessionFactory= new SqlSessionFactoryBean();
        sqlSessionFactory.setDataSource(dataSource);
        //添加X(jué)ML目錄
        sqlSessionFactory.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:mybatis/mapper/first/*-mapper.xml"));
        return sqlSessionFactory.getObject();

    }
    @Bean
    public SqlSessionTemplate firstSqlSessionTemplate(@Qualifier("firstSqlSessionFactory") SqlSessionFactory sqlSessionFactory) throws Exception {
        // 使用上面配置的Factory
        SqlSessionTemplate template = new SqlSessionTemplate(sqlSessionFactory);
        return template;
    }
}

second配置

@Configuration
@MapperScan(basePackages = {"com.self.structure.second.dao"}, sqlSessionTemplateRef = "secondSqlSessionTemplate")
public class SecondDruidConfig {
    @Bean(name = "secondDataSource")
    @ConfigurationProperties(prefix = "spring.datasource.second")
    public DataSource secondDataSource() {
        return DataSourceBuilder.create().build();
    }

    @Bean
    public SqlSessionFactory secondSqlSessionFactory(@Qualifier("secondDataSource") DataSource dataSource) throws Exception {
        SqlSessionFactoryBean sqlSessionFactory= new SqlSessionFactoryBean();
        sqlSessionFactory.setDataSource(dataSource);
        //添加X(jué)ML目錄
        sqlSessionFactory.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:mybatis/mapper/second/*-mapper.xml"));
        return sqlSessionFactory.getObject();
    }

    @Bean
    public SqlSessionTemplate secondSqlSessionTemplate(@Qualifier("secondSqlSessionFactory") SqlSessionFactory sqlSessionFactory) throws Exception {
        // 使用上面配置的Factory
        SqlSessionTemplate template = new SqlSessionTemplate(sqlSessionFactory);
        return template;
    }
}

注:first配置中@Primary注解作用是指定項(xiàng)目默認(rèn)數(shù)據(jù)源,也就是項(xiàng)目啟動(dòng)默認(rèn)連接的數(shù)據(jù)源

mybatis-plus對(duì)應(yīng)的配置

  • 相比mybatis的配置要多配置MybatisConfiguration和plugins
    first配置
@Configuration
@MapperScan(basePackages = {"com.self.structure.first.dao"}, sqlSessionTemplateRef = "firstSqlSessionTemplate")
public class FirstDruidConfig {
    @Bean(name = "firstDataSource")
    @Primary
    @ConfigurationProperties(prefix = "spring.datasource.first")
    public DataSource firstDataSource() {
        return DataSourceBuilder.create().build();
    }

    @Bean
    public SqlSessionFactory firstSqlSessionFactory(@Qualifier("firstDataSource") DataSource dataSource) throws Exception {
        SqlSessionFactoryBean sqlSessionFactory= new SqlSessionFactoryBean();
        sqlSessionFactory.setDataSource(dataSource);
        //添加X(jué)ML目錄
        sqlSessionFactory.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:mybatis/mapper/first/*-mapper.xml"));
        //mybatis-plus的額外配置
        MybatisConfiguration configuration = new MybatisConfiguration();
        configuration.setDefaultScriptingLanguage(MybatisXMLLanguageDriver.class);
        configuration.setJdbcTypeForNull(JdbcType.NULL);
        sqlSessionFactory.setConfiguration(configuration);
        sqlSessionFactory.setPlugins(new Interceptor[]{
                new PaginationInterceptor(),
                new PerformanceInterceptor(),
                new OptimisticLockerInterceptor()
        });

        return sqlSessionFactory.getObject();

    }
    @Bean
    public SqlSessionTemplate firstSqlSessionTemplate(@Qualifier("firstSqlSessionFactory") SqlSessionFactory sqlSessionFactory) throws Exception {
        // 使用上面配置的Factory
        SqlSessionTemplate template = new SqlSessionTemplate(sqlSessionFactory);
        return template;
    }
}

second配置

@Configuration
@MapperScan(basePackages = {"com.self.structure.second.dao"}, sqlSessionTemplateRef = "secondSqlSessionTemplate")
public class SecondDruidConfig {
    @Bean(name = "secondDataSource")
    @ConfigurationProperties(prefix = "spring.datasource.second")
    public DataSource secondDataSource() {
        return DataSourceBuilder.create().build();
    }

    @Bean
    public SqlSessionFactory secondSqlSessionFactory(@Qualifier("secondDataSource") DataSource dataSource) throws Exception {
        SqlSessionFactoryBean sqlSessionFactory= new SqlSessionFactoryBean();
        sqlSessionFactory.setDataSource(dataSource);
        //添加X(jué)ML目錄
        sqlSessionFactory.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:mybatis/mapper/second/*-mapper.xml"));
        //mybatis-plus的額外配置
        MybatisConfiguration configuration = new MybatisConfiguration();
        configuration.setDefaultScriptingLanguage(MybatisXMLLanguageDriver.class);
        configuration.setJdbcTypeForNull(JdbcType.NULL);
        sqlSessionFactory.setConfiguration(configuration);
        sqlSessionFactory.setPlugins(new Interceptor[]{
                new PaginationInterceptor(),
                new PerformanceInterceptor(),
                new OptimisticLockerInterceptor()
        });
        return sqlSessionFactory.getObject();
    }

    @Bean
    public SqlSessionTemplate secondSqlSessionTemplate(@Qualifier("secondSqlSessionFactory") SqlSessionFactory sqlSessionFactory) throws Exception {
        // 使用上面配置的Factory
        SqlSessionTemplate template = new SqlSessionTemplate(sqlSessionFactory);
        return template;
    }
}

創(chuàng)建Mapper

  • 接下來(lái)就是和往常一樣創(chuàng)建數(shù)據(jù)源配置中注解@MapperScan(basePackages = {"com.self.structure.first/second.dao"})對(duì)應(yīng)的mybatis/mybatis-plus數(shù)據(jù)訪問(wèn)層了
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容