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

一、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 implements ProductService {
}
@Service
@DS("master")
public class UserServiceImpl extends ServiceImpl implements UserService {
}

三、在pom.xml中添加

 
            com.baomidou
            dynamic-datasource-spring-boot-starter
            3.5.0
        

四、测试

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

你可能感兴趣的:(mybatisplus,mysql,java)