SpringBoot 多数据源及事务解决方案
@Configuration
public class DataSourceConfig {
@Bean
@Primary
@ConfigurationProperties(prefix = "spring.datasource.primary")
public DataSource primaryDataSource() {
return DataSourceBuilder.create().build();
}
@Bean
@ConfigurationProperties(prefix = "spring.datasource.secondary")
public DataSource secondaryDataSource() {
return DataSourceBuilder.create().build();
}
}
@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(
entityManagerFactoryRef = "entityManagerFactoryPrimary",
transactionManagerRef = "transactionManagerPrimary",
basePackages = {"com.example.repository.primary"} // 设置Repository所在位置
)
public class PrimaryDataSourceConfig {
@Primary
@Bean
public LocalContainerEntityManagerFactoryBean entityManagerFactoryPrimary(
EntityManagerFactoryBuilder builder, @Qualifier("primaryDataSource") DataSource dataSource) {
return builder
.dataSource(dataSource)
.packages("com.example.domain.primary") // 设置实体类所在位置
.persistenceUnit("primary")
.build();
}
@Primary
@Bean
public PlatformTransactionManager transactionManagerPrimary(
@Qualifier("entityManagerFactoryPrimary") EntityManagerFactory entityManagerFactory) {
return new JpaTransactionManager(entityManagerFactory);
}
}
@Configuration
@EnableJpaRepositories(
entityManagerFactoryRef = "entityManagerFactorySecondary",
transactionManagerRef = "transactionManagerSecondary",
basePackages = {"com.example.repository.secondary"} // 设置Repository所在位置
)
public class SecondaryDataSourceConfig {
@Bean
public LocalContainerEntityManagerFactoryBean entityManagerFactorySecondary(
EntityManagerFactoryBuilder builder, @Qualifier("secondaryDataSource") DataSource dataSource) {
return builder
.dataSource(dataSource)
.packages("com.example.domain.secondary") // 设置实体类所在位置
.persistenceUnit("secondary")
.build();
}
@Bean
public PlatformTransactionManager transactionManagerSecondary(
@Qualifier("entityManagerFactorySecondary") EntityManagerFactory entityManagerFactory) {
return new JpaTransactionManager(entityManagerFactory);
}
}
在这个代码实例中,我们定义了两个数据源配置类,每
评论已关闭