SpringBoot+MyBatis项目中同时操作多个数据库

在实际项目开发中可能存在需要同时操作两个数据库的场景,比如从A库读取数据,进行操作后往B库中写入数据,此时就需要进行多数据库配置。本文以操作本地和线上的MySQL数据库为例:

MybatislPlus版本可参照官网,进行配置后一个注解就可以解决:MybatisPlust多数据源

Mybatis版本:

1、导入相关pom文件

<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <scope>runtime</scope>
</dependency>

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>

<dependency>
    <groupId>org.mybatis</groupId>
    <artifactId>mybatis</artifactId>
    <version>3.5.5</version>
</dependency>

<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>druid</artifactId>
    <version>1.2.3</version>
</dependency>

<dependency>
    <groupId>org.mybatis</groupId>
    <artifactId>mybatis-spring</artifactId>
    <version>2.0.7</version>
</dependency>

<dependency>
    <groupId>org.projectlombok</groupId>
    <artifactId>lombok</artifactId>
    <optional>true</optional>
</dependency>

二、application.yml配置文件编写

单数据源的配置如下:

spring:
  datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://127.0.0.1:3306/meal_order?useSSL=false&useUnicode=true&characterEncoding=UTF-8&serverTimezone=GMT%2B8
    username: root
    password: root
    type: com.alibaba.druid.pool.DruidDataSource

多数据源的配置如下:

spring:
  datasource:
    dev:
      driver-class-name: com.mysql.cj.jdbc.Driver
      jdbcUrl: jdbc:mysql://xxx.xx.xx.xx:3306/meal_order?useSSL=false&useUnicode=true&characterEncoding=UTF-8&serverTimezone=GMT%2B8
      username: root
      password: root
      type: com.alibaba.druid.pool.DruidDataSource
    local:
      driver-class-name: com.mysql.cj.jdbc.Driver
      jdbcUrl: jdbc:mysql://127.0.0.1:3306/db2021?useSSL=false&useUnicode=true&characterEncoding=UTF-8&serverTimezone=GMT%2B8
      username: root
      password: root
      type: com.alibaba.druid.pool.DruidDataSource

经过对比可以发现:
1、多数据源的配置中需要指定具体的名称来区分不同的数据库(上述配置中的dev和local,名称可以根据具体需求自定义)
2、需要使用jdbcUrl代替url

三、数据库连接配置文件

dev数据源配置文件:

@Configuration
@MapperScan(basePackages = "com.multiple.mapper.dev",sqlSessionFactoryRef = "devSqlSessionFactory")
public class DevDataSourceConfig {
    @Primary
    @Bean(name = "devDataSource")
    @ConfigurationProperties("spring.datasource.dev")
    public DataSource masterDataSource(){
        return DataSourceBuilder.create().build();
    }

    @Bean(name = "devSqlSessionFactory")
    public SqlSessionFactory sqlSessionFactory(@Qualifier("devDataSource") DataSource dataSource) throws Exception {
        SqlSessionFactoryBean sessionFactoryBean = new SqlSessionFactoryBean();
        sessionFactoryBean.setDataSource(dataSource);
        sessionFactoryBean.setMapperLocations(new PathMatchingResourcePatternResolver()
                .getResources("classpath:mapping/dev/*.xml"));
        return sessionFactoryBean.getObject();
    }
}

local数据源配置文件:

@Configuration
@MapperScan(basePackages = "com.multiple.mapper.local",sqlSessionFactoryRef = "localSqlSessionFactory")
public class LocalDataSourceConfig {
    @Primary
    @Bean(name = "localDataSource")
    @ConfigurationProperties("spring.datasource.local")
    public DataSource masterDataSource(){
        return DataSourceBuilder.create().build();
    }

    @Bean(name = "localSqlSessionFactory")
    public SqlSessionFactory sqlSessionFactory(@Qualifier("localDataSource") DataSource dataSource) throws Exception {
        SqlSessionFactoryBean sessionFactoryBean = new SqlSessionFactoryBean();
        sessionFactoryBean.setDataSource(dataSource);
        sessionFactoryBean.setMapperLocations(new PathMatchingResourcePatternResolver()
                .getResources("classpath:mapping/local/*.xml"));
        return sessionFactoryBean.getObject();
    }
}

不同配置文件通过@MapperScan注解的内容来区分不同数据库下的mapper文件,通过@ConfigurationProperties注解来加载指定的数据源

以DevDataSourceConfig为例
在这里插入图片描述

四、主启动类注解修改

@SpringBootApplication(exclude={DataSourceAutoConfiguration.class})

目录结构如下:
在这里插入图片描述

五、测试

从dev库中查询数据,取出字段插入local库中:

public interface DevMapper {
    @Select("select * from test")
    List<Test> getAllTest();
}
public interface LocalMapper {
    @Insert("insert into payment(serial) values (#{name})")
    int insertMessage(String name);
}
@SpringBootTest
class MultipleDatabaseApplicationTests {

    @Autowired
    private DevMapper devMapper;

    @Autowired
    private LocalMapper localMapper;

    @Test
    void contextLoads() {
        List<com.multiple.pojo.Test> testList = devMapper.getAllTest();
        for(com.multiple.pojo.Test test : testList){
            localMapper.insertMessage(test.getAa());
        }
    }
}

运行测试代码,从dev库中查出的数据可以成功添加至local库
该方法也适用需要使用多种不同的数据库的场景,比如MySQL和Oracle,修改数据源配置文件即可

  • 16
    点赞
  • 129
    收藏
    觉得还不错? 一键收藏
  • 15
    评论
好的,针对你的问题,我可以给出以下解决方案: 1. 首先,需要在新的数据库建立与源数据库相同结构的表,可以使用 Navicat 等工具进行快速同步数据库结构。 2. 接着,需要在 SpringBoot 项目配置两个数据源,一个是源数据库的数据源,另一个是目标数据库的数据源。可以使用 SpringBoot 自带的多数据源配置方式,或者使用第三方库,比如 Druid。 3. 然后,需要编写数据同步的逻辑,可以使用 MyBatis 读取源数据库的数据,然后使用 MyBatis 写入到目标数据库。具体实现可以参考以下代码: ```java @Service public class DataSyncService { @Autowired private DataSource sourceDataSource; @Autowired private DataSource targetDataSource; @Autowired private SqlSessionFactory sourceSqlSessionFactory; @Autowired private SqlSessionFactory targetSqlSessionFactory; public void syncData() { // 从源数据库读取数据 SqlSession sourceSession = sourceSqlSessionFactory.openSession(); List<SourceData> sourceDataList = sourceSession.selectList("sourceMapper.selectData"); sourceSession.close(); // 写入目标数据库 SqlSession targetSession = targetSqlSessionFactory.openSession(); TargetMapper targetMapper = targetSession.getMapper(TargetMapper.class); for (SourceData sourceData : sourceDataList) { TargetData targetData = convertToTargetData(sourceData); targetMapper.insertData(targetData); } targetSession.commit(); targetSession.close(); } private TargetData convertToTargetData(SourceData sourceData) { // 实现数据转换逻辑 TargetData targetData = new TargetData(); targetData.setId(sourceData.getId()); targetData.setName(sourceData.getName()); // ... return targetData; } } ``` 需要注意的是,建议使用批量插入的方式,可以大大提高数据同步的效率。 4. 最后,可以使用定时任务等方式定时调用数据同步的逻辑,保证数据的实时同步。 以上就是一个简单的基于 SpringBootMyBatisMySQL 实现数据库数据同步的方案,希望对你有所帮助。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 15
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值