一、环境
<!-- spring web 基础 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- mysql 连接包 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<!-- mybatis plus -->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.5.1</version>
</dependency>
<!-- mybatis Plus 多数据源 -->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>dynamic-datasource-spring-boot-starter</artifactId>
<version>3.4.1</version>
</dependency>
二、配置
spring:
datasource:
dynamic:
primary: master
strict: false
datasource:
master:
url: jdbc:mysql://localhost:3306/study_demo?serverTimezone=UTC&useUnicode=true&characterEncoding=utf8&useSSL=false
username: root
password: root
slave:
url: jdbc:mysql://localhost:3306/study_demo2?serverTimezone=UTC&useUnicode=true&characterEncoding=utf8&useSSL=false
username: root
password: root
三、使用
1、Mapper
@Mapper
@DS("master")
public interface Student1Mapper extends BaseMapper<Student> {
}
@Mapper
@DS("slave")
public interface Student2Mapper extends BaseMapper<Student> {
}
2、Demo
@Autowired
private StudentMapper studentMapper;
@Test
void moreDatasource(){
System.out.println(student1Mapper.selectList(new QueryWrapper<>()).get(0));
System.out.println(student2Mapper.selectList(new QueryWrapper<>()).get(0));
}
3、结果
Student(id=1, name=demo1, sex=null, grade=null)
Student(id=33, name=demo2, sex=null, grade=null)
|