mybatis-plus多数据源配置
时间: 2023-04-30 19:00:05 浏览: 172
Mybatis-Plus支持多数据源配置,可以通过配置多个数据源来实现在不同的数据库中进行数据操作。具体配置步骤如下:
1. 在application.properties文件中配置多个数据源的连接信息,例如:
```
# 数据源1
spring.datasource.url=jdbc:mysql://localhost:3306/db1?useUnicode=true&characterEncoding=utf-8&useSSL=false
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
# 数据源2
spring.datasource.test2.url=jdbc:mysql://localhost:3306/db2?useUnicode=true&characterEncoding=utf-8&useSSL=false
spring.datasource.test2.username=root
spring.datasource.test2.password=root
spring.datasource.test2.driver-class-name=com.mysql.jdbc.Driver
```
2. 在Mybatis-Plus的配置文件中配置多个SqlSessionFactory,例如:
```
@Configuration
public class MybatisPlusConfig {
@Bean(name = "test1SqlSessionFactory")
public SqlSessionFactory test1SqlSessionFactory(@Qualifier("test1DataSource") DataSource dataSource) throws Exception {
MybatisSqlSessionFactoryBean bean = new MybatisSqlSessionFactoryBean();
bean.setDataSource(dataSource);
bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath*:mapper/test1/*.xml"));
return bean.getObject();
}
@Bean(name = "test2SqlSessionFactory")
public SqlSessionFactory test2SqlSessionFactory(@Qualifier("test2DataSource") DataSource dataSource) throws Exception {
MybatisSqlSessionFactoryBean bean = new MybatisSqlSessionFactoryBean();
bean.setDataSource(dataSource);
bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath*:mapper/test2/*.xml"));
return bean.getObject();
}
}
```
3. 在Mybatis-Plus的配置文件中配置多个MapperScannerConfigurer,例如:
```
@Configuration
public class MybatisPlusConfig {
@Bean(name = "test1MapperScannerConfigurer")
public MapperScannerConfigurer test1MapperScannerConfigurer() {
MapperScannerConfigurer configurer = new MapperScannerConfigurer();
configurer.setBasePackage("com.example.mapper.test1");
configurer.setSqlSessionFactoryBeanName("test1SqlSessionFactory");
return configurer;
}
@Bean(name = "test2MapperScannerConfigurer")
public MapperScannerConfigurer test2MapperScannerConfigurer() {
MapperScannerConfigurer configurer = new MapperScannerConfigurer();
configurer.setBasePackage("com.example.mapper.test2");
configurer.setSqlSessionFactoryBeanName("test2SqlSessionFactory");
return configurer;
}
}
```
4. 在Mapper接口中使用@Mapper注解指定对应的SqlSessionFactory,例如:
```
@Mapper
public interface Test1Mapper {
// ...
}
@Mapper
public interface Test2Mapper {
// ...
}
```
这样就可以在不同的Mapper接口中使用不同的数据源进行数据操作了。
阅读全文