Java学习 --- mybatisplus配置多数据源

本文介绍了如何在Spring Boot应用中使用MyBatisPlus配置多数据源,包括主从数据源的定义,@DS注解在Service层的使用,以及在测试中验证数据源切换的正确性。通过动态数据源配置,可以方便地在不同数据库间进行读写操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一、mybatisplus配置多数据源

spring:
  # 配置多数据源信息
  datasource:
    # 配置数据源类型
    dynamic:
      # 设置默认数据源或者数据源组
      primary: master
      strict: false
      datasource:
        master:
          url: jdbc:mysql://localhost:3307/mybatis_plus?characterEncoding=utf-8&SSL=false
          driver-class-name: com.mysql.cj.jdbc.Driver
          username: root
          password: 123456
        slave_1:
          url: jdbc:mysql://localhost:3307/mybatis_plus_1?characterEncoding=utf-8&SSL=false
          driver-class-name: com.mysql.cj.jdbc.Driver
          username: root
          password: 123456
mybatis-plus:
  configuration:
    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
    # 配置统一表的前缀名
  global-config:
    db-config:
      table-prefix: t_
      # 配置全局的主键生成策略
      id-type: auto
  # 配置包的别名
  type-aliases-package: com.cjc.mybatisplus.pojo
  #配置扫描枚举包
  type-enums-package: com.cjc.mybatisplus.enums

二、在service实现类上添加@DS


@Service
@DS("slave_1")
public class ProductServiceImpl extends ServiceImpl<ProductMapper,Product> implements ProductService {
}
@Service
@DS("master")
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
}

三、在pom.xml中添加

 <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>dynamic-datasource-spring-boot-starter</artifactId>
            <version>3.5.0</version>
        </dependency>

四、测试

@SpringBootTest
public class MultiSourceTest {
    @Autowired
    private UserService userService;
    @Autowired
    private ProductService productService;

    @Test
    public void Test01(){
        User byId = userService.getById(3);
        System.out.println(byId);
        Product byId1 = productService.getById(1);
        System.out.println(byId1);
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

鸭鸭老板

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值