展开
拓展 关闭
订阅号推广码
GitHub
视频
公告栏 关闭

多数据源

  • 将之前的数据库作为主库,删除product表,只保留user表
  • 再创建1个数据库作为从库,同时创建product表
  • 创建1个spring boot项目,再之前依赖的基础上引入如下依赖
<dependency>
    <groupId>com.baomidou</groupId>
    <artifactId>dynamic-datasource-spring-boot-starter</artifactId>
    <version>3.5.0</version>
</dependency>
  • 配置application.yml
spring:
  # 配置数据源信息
  datasource:
    dynamic:
      # 设置默认的数据源或者数据源组,默认值即为master
      primary: master
      # 严格匹配数据源,默认false.true未匹配到指定数据源时抛异常,false使用默认数据源
      strict: false
      datasource:
        master:
          url: jdbc:mysql://localhost:3306/mybatis_plus?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?characterEncoding=utf-8&useSSL=false
          driver-class-name: com.mysql.cj.jdbc.Driver
          username: root
          password: 123456
  • 启动类添加注解
@MapperScan("com.atguigu.mybatisplus.mapper")
  • 实体类
@Data
@TableName("t_user")
public class User {

    @TableId
    private Integer uid;

    private String userName;

    private Integer age;

    private Integer sex;

    private String email;

    private Integer isDeleted;

}

@Data
public class Product {

    private Integer id;

    private String name;

    private Integer price;

    private Integer version;

}
  • mapper接口
@Repository
public interface UserMapper extends BaseMapper<User> {
}

@Repository
public interface ProductMapper extends BaseMapper<Product> {
}
  • 业务层接口
public interface UserService extends IService<User> {
}

public interface ProductService extends IService<Product> {
}
  • 业务层实现
@Service
@DS("master")
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
}

@Service
@DS("slave_1")
public class ProductServiceImpl extends ServiceImpl<ProductMapper, Product> implements ProductService {
}
  • 测试
@SpringBootTest
class MybatisPlusDatasourceApplicationTests {

	@Test
	void contextLoads() {
	}

	@Autowired
	private UserService userService;
	@Autowired
	private ProductService productService;

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

}
  • 拓展
@DS("master")可以添加在类或方法上
posted @ 2022-07-08 15:56  DogLeftover  阅读(20)  评论(0编辑  收藏  举报