MybatisPlus多数据源

适用于多种场景:纯粹多库、 读写分离、 一主多从、 混合模式等
目前我们就来模拟一个纯粹多库的一个场景,其他场景类似
以下的案例是使用多个数据库
准备工作在不同的数据库中创建不同的表分别为t_user 和product
启动类记得加MapperScan注解
第一步:首先创建好springboot项目之后,假如依赖

    org.springframework.boot
    spring-boot-starter



    org.projectlombok
    lombok
    true


    org.springframework.boot
    spring-boot-starter-test
    test


    com.baomidou
    mybatis-plus-boot-starter
    3.5.1


    org.projectlombok
    lombok
    true


    mysql
    mysql-connector-java
    runtime


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

第二步application中设置数据源

spring:
# 配置数据源信息
  datasource:
    dynamic:
# 设置默认的数据源或者数据源组,默认值即为master
       primary: master
# 严格匹配数据源,默认false.true未匹配到指定数据源时抛异常,false使用默认数据源
       strict: false
       datasource: #设置两个数据源
         master:
           url: jdbc:mysql://localhost:3306/mybatis_plus?serverTimezone=GMT%2B8&characterEncoding=utf-8&useSSL=false
           driver-class-name: com.mysql.cj.jdbc.Driver
           username: root
           password: 123456
         slave_1:
           url: jdbc:mysql://localhost:3306/mybatis_plus_1?serverTimezone=GMT%2B8&characterEncoding=utf-8&useSSL=false
           driver-class-name: com.mysql.cj.jdbc.Driver
           username: root
           password: 123456

实体类

@Data
@AllArgsConstructor
@NoArgsConstructor
@TableName("t_user")
public class User {
    //@TableId//id和id的名字不一样的时候,实体类和数据表中都使用uid的时候

    /*实体类中是id,数据表中是uid的时候,使用value指定唯一的键
    * type = IdType.AUTO,表示自增的主键,不使用这个新增后自增使用的是雪花算法
    * */
    @TableId(value = "uid",type = IdType.AUTO)
    private Long id;
    private String name;
    private Integer age;
    private String email;
}
@Data
public class Product {
    private Integer id;
    private String name;
    private Integer price;
    @Version//用来标识乐观锁版本号字段
    private Integer version;
}

-----------------------------------------------------------------------

mapper层

@Repository
public interface UserMapper extends BaseMapper {
}
@Repository
public interface ProductMapper extends BaseMapper {
}

-----------------------------------------------------------------------

service层

public interface UserService extends IService {
}
@DS("master") //指定所操作的数据源,在application.yml中配置,可以加到方法上代表在指定方法操作指定的数据源
@Service
public class UserServiceImpl extends ServiceImpl implements UserService {
}
public interface ProductService extends IService {
}
@DS("slave_1")
@Service
public class ProductServiceImpl extends ServiceImpl implements ProductService {
}

-----------------------------------------------------------------------

测试类

@SpringBootTest
public class MybatisPlusDataSourceApplicationTests {
    @Autowired
    private UserService userService;//注意这里用的是service
    @Autowired
    private ProductService productService;

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

        System.out.println(productService.getById(1L));
    }

}

两个查询两个数据库,都可以查到

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