springboot+mybatis/mybatis-plus+druid配置多数据源

养成良好的记录习惯
作者:黄黄

最近公司业务要求查询不同数据库的数据组装在一起,所以需要进行多数据源配置的操作。

yml添加配置

  • 这里以sqlsever数据库为例,其他数据库也类似
  • 这里列举first和second两个数据源
  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
        #最大等待时间,配置获取连接等待超时,时间单位都是毫秒ms
        max-wait: 60000
        #配置间隔多久才进行一次检测,检测需要关闭的空闲连接
        time-between-eviction-runs-millis: 60000
        #配置一个连接在池中最小生存的时间
        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
        #最大等待时间,配置获取连接等待超时,时间单位都是毫秒ms
        max-wait: 60000
        #配置间隔多久才进行一次检测,检测需要关闭的空闲连接
        time-between-eviction-runs-millis: 60000
        #配置一个连接在池中最小生存的时间
        min-evictable-idle-time-millis: 300000

这里列举几个小细节

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

添加数据源配置

mybatis对应的配置

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);
        //添加XML目录
        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);
        //添加XML目录
        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注解作用是指定项目默认数据源,也就是项目启动默认连接的数据源

mybatis-plus对应的配置

  • 相比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);
        //添加XML目录
        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);
        //添加XML目录
        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;
    }
}

创建Mapper

  • 接下来就是和往常一样创建数据源配置中注解@MapperScan(basePackages = {"com.self.structure.first/second.dao"})对应的mybatis/mybatis-plus数据访问层了

你可能感兴趣的:(springboot+mybatis/mybatis-plus+druid配置多数据源)