MybatisPlus配置多数据源

1.准备好两个数据库

mybatis_plus表当中有product

mybatis_plus1表中有user

2.导入依赖

XML 复制代码
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>dynamic-datasource-spring-boot-starter</artifactId>
            <version>3.5.0</version>
        </dependency>

3.指定数据源

在ProductServiceImpl和UserServiceImpl上使用@DS注解指明要使用的数据源

4.配置新数据源

修改application.yaml配置:

这里配置的primary:master表示的是在没有明确指明数据库的业务下,使用默认的master数据源

diff 复制代码
spring:
  datasource:
    dynamic:
      # 设置默认的数据源或者数据源组 ,默认值即为master
      primary: master
      # 严格匹配数据源 ,默认false.true未匹配到指定数据源时抛异常 ,false使用默认数据源
      strict: false
      datasource:
        #master:product表
        master:
          type: com.zaxxer.hikari.HikariDataSource
          driver-class-name: com.mysql.cj.jdbc.Driver
          url: jdbc:mysql://localhost:3306/mybatis_plus?characterEncoding=utf-8&useSSL=false
          username: root
          password: root
        #slave_1:user表
        slave_1:
          type: com.zaxxer.hikari.HikariDataSource
          driver-class-name: com.mysql.cj.jdbc.Driver
          url: jdbc:mysql://localhost:3306/mybatis_plus1?characterEncoding=utf-8&useSSL=false
          username: root
          password: root
mybatis-plus:
  configuration:
    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
  global-config:
    db-config:
      table-prefix: t_
  type-enums-package: com.qcby.enums

5.进行测试

编写测试类:

java 复制代码
package com.qcby;

import com.qcby.service.ProductService;
import com.qcby.service.UserService;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

@SpringBootTest
public class MybatisTestSource {

    @Autowired
    private UserService userService;

    @Autowired
    private ProductService productService;

    @Test
    public void testDynamicDataSource(){
        System.out.println(userService.getById(1L));
        System.out.println(productService.getById(1L));
    }
}

都能查询到说明配置成功了

相关推荐
c***72741 小时前
MySQL查看日志
数据库·mysql
321茄子1 小时前
MySQL 事务隔离性及锁
java·数据库·mysql
w***95491 小时前
MySQL无法连接到本地localhost的解决办法2024.11.8
数据库·mysql·adb
z***3351 小时前
PON架构(全光网络)
网络·数据库·架构
n***78681 小时前
PostgreSQL 中进行数据导入和导出
大数据·数据库·postgresql
f***S2441 小时前
MyBatis-Plus 自定义 SQL 和复杂查询
数据库·sql·mybatis
1***Q7841 小时前
后端在微服务中的服务路由
java·数据库·微服务
R***62311 小时前
Spring数据库原理 之 DataSource
java·数据库·spring
h***38181 小时前
使用python进行PostgreSQL 数据库连接
数据库·python·postgresql