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));
    }
}

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

相关推荐
XDHCOM2 天前
ORA-32484重复列名错误,ORACLE数据库CYCLE子句故障修复与远程处理方案
数据库·oracle
翻斗包菜2 天前
PostgreSQL 日常维护完全指南:从基础操作到高级运维
运维·数据库·postgresql
呆瑜nuage2 天前
MySQL表约束详解:8大核心约束实战指南
数据库·mysql
liliangcsdn2 天前
Agent Memory智能体记忆系统的示例分析
数据库·人工智能·全文检索
那个失眠的夜2 天前
Mybatis延迟加载策略
xml·java·数据库·maven·mybatis
Rick19932 天前
SQL 执行流程
数据库·sql
M--Y2 天前
Redis常用数据类型
数据结构·数据库·redis
猿小喵2 天前
MySQL慢查询分析与处理-第二篇
数据库·mysql·性能优化
Y001112362 天前
MySQL-进阶
开发语言·数据库·sql·mysql
徒 花2 天前
数据库知识复习01
数据库