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

时间:2025-03-08 07:50:44

一、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: 
          username: root
          password: 123456
        slave_1:
          url: jdbc:mysql://localhost:3307/mybatis_plus_1?characterEncoding=utf-8&SSL=false
          driver-class-name: 
          username: root
          password: 123456
mybatis-plus:
  configuration:
    log-impl: 
    # 配置统一表的前缀名
  global-config:
    db-config:
      table-prefix: t_
      # 配置全局的主键生成策略
      id-type: auto
  # 配置包的别名
  type-aliases-package: 
  #配置扫描枚举包
  type-enums-package: 

二、在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 {
}

三、在中添加

 <dependency>
            <groupId></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 = (3);
        (byId);
        Product byId1 = (1);
        (byId1);
    }
}