SpringBoot中配置与使用MybatisPlus提供的多数据源【只需两步】
在SpringBoot项目中配置和使用MyBatis-Plus提供的多数据源,通常需要以下两个步骤:
- 配置多个数据源
- 配置多个MyBatis-Plus的
SqlSessionFactory
和MapperScanner
以下是一个简化的示例代码:
第一步:配置多数据源
@Configuration
public class DataSourceConfig {
@Bean
@ConfigurationProperties("spring.datasource.primary")
public DataSource primaryDataSource() {
return DataSourceBuilder.create().build();
}
@Bean
@ConfigurationProperties("spring.datasource.secondary")
public DataSource secondaryDataSource() {
return DataSourceBuilder.create().build();
}
}
第二步:配置多个SqlSessionFactory和MapperScanner
@Configuration
public class MybatisPlusConfig {
@Bean
public MybatisSqlSessionFactoryBean primarySqlSessionFactory(@Qualifier("primaryDataSource") DataSource primaryDataSource) {
MybatisSqlSessionFactoryBean sqlSessionFactory = new MybatisSqlSessionFactoryBean();
sqlSessionFactory.setDataSource(primaryDataSource);
return sqlSessionFactory;
}
@Bean
public MybatisSqlSessionFactoryBean secondarySqlSessionFactory(@Qualifier("secondaryDataSource") DataSource secondaryDataSource) {
MybatisSqlSessionFactoryBean sqlSessionFactory = new MybatisSqlSessionFactoryBean();
sqlSessionFactory.setDataSource(secondaryDataSource);
return sqlSessionFactory;
}
@Bean
public MapperScannerConfigurer primaryMapperScanner() {
MapperScannerConfigurer mapperScanner = new MapperScannerConfigurer();
mapperScanner.setSqlSessionFactoryBeanName("primarySqlSessionFactory");
mapperScanner.setBasePackage("com.example.primary.mapper");
return mapperScanner;
}
@Bean
public MapperScannerConfigurer secondaryMapperScanner() {
MapperScannerConfigurer mapperScanner = new MapperScannerConfigurer();
mapperScanner.setSqlSessionFactoryBeanName("secondarySqlSessionFactory");
mapperScanner.setBasePackage("com.example.secondary.mapper");
return mapperScanner;
}
}
在这个配置中,你需要为每个数据源定义一个DataSource
,一
评论已关闭