【项目】SpringBoot +MybatisPlus集成多数据源

引言

应项目需求,需要引入另外的Mysql数据库,但是项目已经引入一个Mysql,这时有几种方案

  1. 通过Dynamic-DataSource 框架,无缝集成 但是是动态切换数据源的,跟项目需求不符合,于是采取第二种
  2. 通过自定义数据源配置类,无缝引入多个数据源,并且基于文件目录隔离

步骤

引入依赖

项目需要引入了MyBatis Plus即可,无需引入额外依赖

xml 复制代码
<dependency>
    <groupId>com.baomidou</groupId>
    <artifactId>mybatis-plus-boot-starter</artifactId>
    <version>3.5.12</version>
</dependency>

修改配置文件

yml 复制代码
spring:
  datasource:
    d1:
      password: xxxx
      username: xxxx
      jdbc-url: jdbc:mysql://xxxx:3306/ecshop_wp?characterEncoding=utf-8&useSSL=false&serverTimezone=Asia/Shanghai&allowPublicKeyRetrieval=true
      driver-class-name: com.mysql.cj.jdbc.Driver
    d2:
      password: root
      username: root
      jdbc-url: jdbc:mysql://127.0.0.1:3306/xg_bi_lcc?characterEncoding=utf-8&useSSL=false&serverTimezone=Asia/Shanghai&allowPublicKeyRetrieval=true
      driver-class-name: com.mysql.cj.jdbc.Driver

添加配置类

java 复制代码
@Configuration
@MapperScan(basePackages = "xg.xx.model.front.service.mysql.mapper1", sqlSessionFactoryRef = "d1SqlSessionFactory")
public class EcshopWpDataSourceConfig {

    @Bean(name = "d1DataSource")
    @ConfigurationProperties(prefix = "spring.datasource.d1")
    public DataSource ecshopWpDataSource() {
        return DataSourceBuilder.create().build();
    }

    @Bean(name = "d1SqlSessionFactory")
    public SqlSessionFactory ecshopWpSqlSessionFactory(@Qualifier("d1DataSource") DataSource dataSource) throws Exception {
        MybatisSqlSessionFactoryBean bean = new MybatisSqlSessionFactoryBean();
        //configuration配置bean
        //MybatisConfiguration configuration = new MybatisConfiguration();
        //configuration.setMapUnderscoreToCamelCase(true);
        //configuration.setCacheEnabled(false);
        // 配置打印sql语句s
        //configuration.setLogImpl(StdOutImpl.class);
        // 添加自定义SQL注入
        //bean.setConfiguration(configuration);

        //插件对象
        MybatisPlusInterceptor mybatisPlusInterceptor = new MybatisPlusInterceptor();
        //动态表名
        //DynamicTableNameInnerInterceptor dynamicTableNameInnerInterceptor = new DynamicTableNameInnerInterceptor();
        //可以传多个表名参数,指定哪些表使用MonthTableNameHandler处理表名称
        //dynamicTableNameInnerInterceptor.setTableNameHandler(new MonthTableNameHandler("t_table_name"));
        //以拦截器的方式处理表名称
        //可以传递多个拦截器,即:可以传递多个表名处理器TableNameHandler
        //mybatisPlusInterceptor.addInnerInterceptor(dynamicTableNameInnerInterceptor);


        //分页插件
        mybatisPlusInterceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
        bean.setDataSource(dataSource);
        // 设置mybatis的xml所在位置
        bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath*:mybatis/d1/*.xml"));
        bean.setPlugins(mybatisPlusInterceptor);
        return bean.getObject();
    }

    @Bean(name = "d1TransactionManager")
    public DataSourceTransactionManager ecshopWpTransactionManager(@Qualifier("d1DataSource") DataSource dataSource) {
        return new DataSourceTransactionManager(dataSource);
    }
}
java 复制代码
@Configuration
@MapperScan(basePackages = "xg.xx.model.front.service.mysql.Mapper2", sqlSessionFactoryRef = "d2SqlSessionFactory")
public class XgBiLccDataSourceConfig {

    @Bean(name = "d2DataSource")
    @ConfigurationProperties(prefix = "spring.datasource.d2")
    public DataSource ecshopWpDataSource() {
        return DataSourceBuilder.create().build();
    }

    @Bean(name = "d2SqlSessionFactory")
    public SqlSessionFactory ecshopWpSqlSessionFactory(@Qualifier("d2DataSource") DataSource dataSource) throws Exception {
        MybatisSqlSessionFactoryBean bean = new MybatisSqlSessionFactoryBean();
        //configuration配置bean
        //MybatisConfiguration configuration = new MybatisConfiguration();
        //configuration.setMapUnderscoreToCamelCase(true);
        //configuration.setCacheEnabled(false);
        // 配置打印sql语句s
        //configuration.setLogImpl(StdOutImpl.class);
        // 添加自定义SQL注入
        //bean.setConfiguration(configuration);

        //插件对象
        MybatisPlusInterceptor mybatisPlusInterceptor = new MybatisPlusInterceptor();
        //动态表名
        //DynamicTableNameInnerInterceptor dynamicTableNameInnerInterceptor = new DynamicTableNameInnerInterceptor();
        //可以传多个表名参数,指定哪些表使用MonthTableNameHandler处理表名称
        //dynamicTableNameInnerInterceptor.setTableNameHandler(new MonthTableNameHandler("t_table_name"));
        //以拦截器的方式处理表名称
        //可以传递多个拦截器,即:可以传递多个表名处理器TableNameHandler
        //mybatisPlusInterceptor.addInnerInterceptor(dynamicTableNameInnerInterceptor);


        //分页插件
        mybatisPlusInterceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
        bean.setDataSource(dataSource);
        // 设置mybatis的xml所在位置
        bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath*:mybatis/d2/*.xml"));
        bean.setPlugins(mybatisPlusInterceptor);
        return bean.getObject();
    }

    @Bean(name = "d2TransactionManager")
    public DataSourceTransactionManager ecshopWpTransactionManager(@Qualifier("d2DataSource") DataSource dataSource) {
        return new DataSourceTransactionManager(dataSource);
    }
}

使用案例

@Transactional

java 复制代码
@Transactional(value = "d2TransactionManager", rollbackFor = Exception.class)
这样即可进行全局事物管理
相关推荐
考虑考虑31 分钟前
zookeeper认证
后端·zookeeper
掘金者阿豪1 小时前
数据库选型到底应该看什么?从业务需求到技术架构的实践分析
前端·后端
codigger1 小时前
ThreadLocal 会内存泄露吗?
java·内存泄漏·threadlocal
挖掘狂人1 小时前
ThreadLocal 会内存泄露吗?
java·安全·架构
她的男孩1 小时前
审批人选了「部门主管」,发起却报 Unknown property:Forge Admin 启动时补齐组织变量
spring boot·低代码·工作流引擎
苍何1 小时前
豆包终于想通了...
后端
AAA修煤气灶刘哥2 小时前
Agent 都能干活了,软件还需要那么多按钮吗?
人工智能·后端·架构
未秃头的程序猿2 小时前
给新模块加了个 @MapperScan,启动崩了,最后发现跟 MapperScan 没关系
java·后端·mybatis
苍何2 小时前
不用 Opus5.5 ,即梦也能出爆款 vibe 视频了
后端
SimonKing2 小时前
WorkBuddy又推出新的限免模型(Hy4 flash)了,羊毛可以薅起来了
java·后端·程序员