searchusermenu
  • 发布文章
  • 消息中心
点赞
收藏
评论
分享
原创

SringBoot+MyBatis-Plus+Druid 多数据源配置

2024-07-01 10:01:19
6
0

application.yml配置文件

application.yml 文件中配置两个数据源 db-adb-b

spring:
  datasource:
    druid:
      db-a: # 自定义的key,在配置类需要用到
        driver-class-name: com.mysql.cj.jdbc.Driver
        url: jdbc:mysql://localhost:3306/db_a?characterEncoding=utf8&serverTimezone=GMT%2B8
        username: root
        password: 123456
      db-b:
        driver-class-name: com.mysql.cj.jdbc.Driver
        url: jdbc:mysql://localhost:3306/db_b?characterEncoding=utf8&serverTimezone=GMT%2B8
        username: root
        password: 123456

启动类

在单数据源配置中,我们通常在 Spring Boot 启动类中启用 @MapperScan 注解来指定 Mapper 接口所在的包路径。然而,在多数据源配置中,我们需要分别在各自的配置类中指定 @MapperScan,以便实现对不同数据源的 Mapper 扫描。

以下是 Spring Boot 启动类的示例:

@SpringBootApplication(scanBasePackages = {"com.example.demo"})
//@MapperScan("com.example.demo.**.dao") // 不需要在这里配置,由 DataSourceConfigA 和 DataSourceConfigB 配置
public class DemoApplication {
  public static void main(String[] args) {
    SpringApplication.run(DemoApplication.class, args);
  }
}

数据源A配置类

@Configuration
@MapperScan(basePackages = {"com.example.demo.dao"}, // 包扫描路径,即该数据源对应的mapper类在哪些包下
            sqlSessionTemplateRef  = "sqlSessionTemplateA")
public class DataSourceConfigA {

    @Primary
    @Bean(name = "dataSourceA")
    @ConfigurationProperties(prefix = "spring.datasource.druid.db-a") // 对应yml里的key
    public DataSource dataSourceA() {
        return DruidDataSourceBuilder.create().build();
    }

    @Primary
    @Bean(name = "sqlSessionFactoryA")
    public SqlSessionFactory sqlSessionFactoryA(@Qualifier("dataSourceA") DataSource dataSource) throws Exception {
        MybatisSqlSessionFactoryBean bean = new MybatisSqlSessionFactoryBean(); // 使用MyBatis-Plus的话,这里一定要是MybatisSqlSessionFactoryBean,不能是SqlSessionFactoryBean
        bean.setDataSource(dataSource);
        bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:mapper/*.xml"));

        // 设置字段填充控制器(如有的话)
        GlobalConfig globalConfig=new GlobalConfig();
        globalConfig.setMetaObjectHandler(new BizMetaObjectHandler());
        globalConfig.setBanner(false);
        bean.setGlobalConfig(globalConfig);

        return bean.getObject();
    }

    @Primary
    @Bean(name = "transactionManagerA")
    public DataSourceTransactionManager transactionManagerA(@Qualifier("dataSourceA") DataSource dataSource) {
        return new DataSourceTransactionManager(dataSource);
    }

    @Primary
    @Bean(name = "sqlSessionTemplateA")
    public SqlSessionTemplate sqlSessionTemplateA(@Qualifier("sqlSessionFactoryA") SqlSessionFactory sqlSessionFactory) throws Exception {
        return new SqlSessionTemplate(sqlSessionFactory);
    }
}

数据源B配置类

@Configuration
@MapperScan(basePackages = {"com.other.module.dao"},
        sqlSessionTemplateRef  = "sqlSessionTemplateB")
public class DataSourceConfigB {

    @Bean(name = "dataSourceB")
    @ConfigurationProperties(prefix = "spring.datasource.druid.db-b")
    public DataSource dataSourceB() {
        return DruidDataSourceBuilder.create().build();
    }

    @Bean(name = "sqlSessionFactoryB")
    public SqlSessionFactory sqlSessionFactoryB(@Qualifier("dataSourceB") DataSource dataSource) throws Exception {
        MybatisSqlSessionFactoryBean bean = new MybatisSqlSessionFactoryBean();
        bean.setDataSource(dataSource);
        bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources(
                "classpath*:META-INF/module-b/mapper/*.xml")); // 如果数据源对应的Mapper文件在另一个JAR包或模块中,可以这样写,否则可以参考DataSourceConfigA里的写法
        return bean.getObject();
    }

    @Bean(name = "transactionManagerB")
    public DataSourceTransactionManager transactionManagerB(@Qualifier("dataSourceB") DataSource dataSource) {
        return new DataSourceTransactionManager(dataSource);
    }

    @Bean(name = "sqlSessionTemplateB")
    public SqlSessionTemplate sqlSessionTemplateB(@Qualifier("sqlSessionFactoryB") SqlSessionFactory sqlSessionFactory) throws Exception {
        return new SqlSessionTemplate(sqlSessionFactory);
    }
}

总结

通过上述配置,我们可以轻松实现 Spring Boot 项目中的多数据源管理。每个数据源都有自己独立的配置类和 Mapper 扫描路径,确保了不同数据源之间的隔离和独立性。这种配置方式不仅灵活,而且易于维护和扩展。

0条评论
0 / 1000
全****琪
1文章数
0粉丝数
全****琪
1 文章 | 0 粉丝