Mybatis | Mybatis-plus配置多数据源,连接多数据库

前言

​ 工作的时候,遇到了需要将一个数据库的一些数据插入或更新到另一个数据库。一开始使用insert into TABLE (col1,col2) VALUES (val1,val2) ON DUPLICATE KEY update col1 = "val1"; (这句sql语句的意思是:将val1,val2值插入到TABLE表的col1和col2字段中,如果出现主键或唯一冲突,就进行更新,只将col1值更新为val1)进行数据的插入和更新。但是每次都要对着这一条sql语句进行修改,十分麻烦,就想着能否同时连接两个数据库进行业务处理。

业务逻辑

在这里插入图片描述

使用Mybatis实现

首先,如果你的项目用的是Mybatis,那么以下配置可以实现配置多数据源,连接多数据库的作用。但是,如果你使用的是Mybatis-plus,本人建议使用Mybatis-plus实现更加简单易操作。

1、在yml配置文件中配置多数据库,例如:

spring:
  application:
    name: CONNECTION
  datasource:
    db1:
      driver-class-name: com.mysql.cj.jdbc.Driver
      jdbc-url: jdbc:mysql://localhost:3306/test?serverTimezone=UTC
      username: root
      password: 123456
      type: com.alibaba.druid.pool.DruidDataSource
    db2:
      driver-class-name: com.mysql.cj.jdbc.Driver
      jdbc-url: jdbc:mysql://11.11.11.11:3306/test?serverTimezone=UTC
      username: root
      password: 654321
      type: com.alibaba.druid.pool.DruidDataSource

注意,将数据库配置中的url改为jdbc-url,否则无法配置多数据源。

2、创建不同的mapper,用于不同的数据库。
请添加图片描述
3、编写数据源的配置类,例如:

import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.io.support.PathMatchingRes
评论 13
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值