Spring Boot 配置双数据源
在Spring Boot中配置双数据源通常涉及以下步骤:
- 配置数据源属性。
- 创建数据源实例。
- 配置
EntityManagerFactory
和TransactionManager
。 - 配置
@Configuration
类来创建两个不同的Spring容器,每个容器使用不同的数据源。
以下是一个简化的示例代码:
@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(
basePackages = "com.example.repository.first",
entityManagerFactoryRef = "firstEntityManager",
transactionManagerRef = "firstTransactionManager")
public class FirstDataSourceConfig {
@Bean
@Primary
@ConfigurationProperties(prefix = "spring.datasource.first")
public DataSource firstDataSource() {
return DataSourceBuilder.create().build();
}
@Bean
public LocalContainerEntityManagerFactoryBean firstEntityManager(EntityManagerFactoryBuilder builder) {
return builder
.dataSource(firstDataSource())
.packages("com.example.entity.first")
.persistenceUnit("first")
.build();
}
@Bean
@Primary
public PlatformTransactionManager firstTransactionManager(
@Qualifier("firstEntityManager") EntityManagerFactory entityManagerFactory) {
return new JpaTransactionManager(entityManagerFactory);
}
}
@Configuration
@EnableJpaRepositories(
basePackages = "com.example.repository.second",
entityManagerFactoryRef = "secondEntityManager",
transactionManagerRef = "secondTransactionManager")
public class SecondDataSourceConfig {
@Bean
@ConfigurationProperties(prefix = "spring.datasource.second")
public DataSource secondDataSource() {
return DataSourceBuilder.create().build();
}
@Bean
public LocalContainerEntityManagerFactoryBean secondEntityManager(EntityManagerFactoryBuilder builder) {
return builder
.dataSource(secondDataSource())
.packages("com.example.entity.second")
.persistenceUnit("second")
.build();
}
@Bean
public PlatformTransaction
评论已关闭