Mybatis Plus配置多数据源
在Spring Boot项目中配置MyBatis Plus支持多数据源,你可以通过以下步骤实现:
- 配置数据源属性
- 配置数据源
- 配置SqlSessionFactory
- 配置事务管理器
- 配置Mapper扫描
以下是一个简单的示例:
@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();
}
@Bean
public SqlSessionFactory sqlSessionFactoryPrimary() throws Exception {
SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean();
factoryBean.setDataSource(primaryDataSource());
return factoryBean.getObject();
}
@Bean
public SqlSessionFactory sqlSessionFactorySecondary() throws Exception {
SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean();
factoryBean.setDataSource(secondaryDataSource());
return factoryBean.getObject();
}
@Bean
public PlatformTransactionManager transactionManagerPrimary(
@Qualifier("primaryDataSource") DataSource dataSource) {
return new DataSourceTransactionManager(dataSource);
}
@Bean
public PlatformTransactionManager transactionManagerSecondary(
@Qualifier("secondaryDataSource") DataSource dataSource) {
return new DataSourceTransactionManager(dataSource);
}
}
在上述配置中,我们定义了两个数据源primaryDataSource
和secondaryDataSource
,并为每个数据源创建了对应的SqlSessionFactory
和PlatformTransactionManager
。
确保在application.properties
或application.yml
中正确配置了数据源属性,例如:
spring:
datasource:
primary:
url: jdbc:mysql://localhost:3306/primary_db
username: user
password: pass
secondary:
url: jdbc:mysql://localhost:3306/secondary_db
username: user
password: pass
对于Mapper接口,你需要为每个数据源指定对应的SqlSessionFac
评论已关闭