pom.xml
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.5.1</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.46</version>
</dependency>
<!--动态数据源-->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>dynamic-datasource-spring-boot-starter</artifactId>
<version>3.5.0</version>
</dependency>
application.yml
spring:
#配置数据源
datasource:
dynamic:
#默认数据源
primary: master
#严格使用数据源 ,false不设置使用默认数据源
strict: false
datasource:
master:
url: jdbc:mysql://localhost:3306/db1?useUnicode=true&characterEncoding=UTF-8
driver-class-name: com.mysql.cj.jdbc.Driver
username: root
password: xxx
slave_1:
url: jdbc:mysql://localhost:3306/db2?useUnicode=true&characterEncoding=UTF-8
driver-class-name: com.mysql.cj.jdbc.Driver
username: root
password: xxx
默认主数据源不需要加注解
打算切换从数据源需要加注解
public interface ProductService extends IService<Product>{
}
在serviceimpl 加使用那个数据源注解
@DS("slave_1")
@Service
public class ProductServiceImpl extends ServiceImpl<ProductMapper,Product> implements ProductService{
}