- 将之前的数据库作为主库,删除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>
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;
}
@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")可以添加在类或方法上