mybatisplus如何进行多数据源配置
时间: 2023-10-04 15:07:43 浏览: 95
Mybatis-Plus支持多数据源配置,具体步骤如下:
1. 在pom.xml中添加多数据源支持的依赖:
```xml
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>dynamic-datasource-spring-boot-starter</artifactId>
<version>x.y.z</version>
</dependency>
```
2. 在application.properties或application.yml中配置数据源信息:
```yaml
spring:
datasource:
dynamic:
primary: ds1
datasource:
ds1:
url: jdbc:mysql://localhost:3306/db1
username: root
password: 123456
driver-class-name: com.mysql.jdbc.Driver
ds2:
url: jdbc:mysql://localhost:3306/db2
username: root
password: 123456
driver-class-name: com.mysql.jdbc.Driver
```
3. 在Mybatis-Plus配置文件中指定数据源:
```java
@Configuration
public class MybatisPlusConfig {
@Bean
public MybatisSqlSessionFactoryBean mybatisSqlSessionFactoryBean(@Qualifier("dynamicDataSource") DataSource dataSource) {
MybatisSqlSessionFactoryBean sqlSessionFactory = new MybatisSqlSessionFactoryBean();
sqlSessionFactory.setDataSource(dataSource);
return sqlSessionFactory;
}
@Bean
public DynamicDataSource dynamicDataSource() {
DynamicDataSource dynamicDataSource = new DynamicDataSource();
Map<Object, Object> dataSourceMap = new HashMap<>();
dataSourceMap.put("ds1", ds1());
dataSourceMap.put("ds2", ds2());
dynamicDataSource.setTargetDataSources(dataSourceMap);
dynamicDataSource.setDefaultTargetDataSource(ds1());
return dynamicDataSource;
}
@Bean
@ConfigurationProperties(prefix = "spring.datasource.dynamic.datasource.ds1")
public DataSource ds1() {
return DruidDataSourceBuilder.create().build();
}
@Bean
@ConfigurationProperties(prefix = "spring.datasource.dynamic.datasource.ds2")
public DataSource ds2() {
return DruidDataSourceBuilder.create().build();
}
}
```
其中,需要注意的是,@ConfigurationProperties(prefix = "spring.datasource.dynamic.datasource.ds1")注解中的prefix需要与application.yml中的配置一致。
4. 使用@DS注解指定使用哪个数据源:
```java
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
@DS("ds1")
public List<User> listByDs1() {
return list();
}
@DS("ds2")
public List<User> listByDs2() {
return list();
}
}
```
这样,在需要使用不同数据源的方法上添加@DS注解即可。
阅读全文