oracle 如何在Spring中创建一个@Transaction来控制两个不同数据库的回滚?

wfauudbj  于 2023-01-12  发布在  Oracle
关注(0)|答案(1)|浏览(305)

我有两个不同的数据库oracle。
我已经使用SpringBoot实现了与两个数据库一起工作的配置:

@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(basePackages = "br.com.xyz.univers.ms.universcontractsync.repository.universcontract",
        entityManagerFactoryRef = "universContractEntityManagerFactory",
        transactionManagerRef= "universContractTransactionManager"
)
public class UniversContractDatasourceConfiguration {

    @Bean
    @ConfigurationProperties("app.datasource.universcontract")
    public DataSourceProperties universContractDataSourceProperties() {
        return new DataSourceProperties();
    }
    @Bean
    @ConfigurationProperties("app.datasource.universcontract.hikari")
    public DataSource universContractDataSource() {
        return universContractDataSourceProperties().initializeDataSourceBuilder()
                .type(HikariDataSource.class).build();
    }

    @Bean(name = "universContractEntityManagerFactory")
    public LocalContainerEntityManagerFactoryBean universContractEntityManagerFactory(
            EntityManagerFactoryBuilder builder) {
        return builder
                .dataSource(universContractDataSource())
                .packages("br.com.xyz.univers.ms.universcontractsync.models.universcontract")
                .build();
    }

    @Bean(name = "universContractTransactionManager")
    public PlatformTransactionManager universContractTransactionManager(
            final @Qualifier("universContractEntityManagerFactory") LocalContainerEntityManagerFactoryBean universContractEntityManagerFactory) {
        if (universContractEntityManagerFactory == null) {
            throw new SyncUnknowException("universContractEntityManagerFactory is null");
        }
        EntityManagerFactory entityManagerFactory = universContractEntityManagerFactory.getObject();
        if (entityManagerFactory == null) {
            throw new SyncUnknowException("entityManagerFactory is null");
        }
        return new JpaTransactionManager(entityManagerFactory);
    }

}

问题是当一个方法调用两个数据库时,我如何控制事务?这是必要的,因为我的方法需要同时调用两个数据库。

方法示例:

@Override
@Transactional("chainedTransactionManager")
public void save(CompanyDTO companyDTO) {
    log.info("method=save  ' - CompanyServiceImpl");
    CompanyDTO companyDTOWithLegacyCode = companyDTO.toBuilder().build();
    legacyCodeService.changeToLegacyCode(companyDTOWithLegacyCode);
    Company company = companyBuilder.universContractDtoToSisbfEntity(companyDTOWithLegacyCode);
    companyRepository.save(company);
    legacyCodeService.updateLegacyCode(ClassTypeEnum.COMPANY, companyDTO.getCompanyCode(), company.getCompanyCode());
    log.info("finish method=save  ' - CompanyServiceImpl");
}
6vl6ewon

6vl6ewon1#

通过显式地指定@Transactional注解的值来为两个数据库使用@Transactional注解,例如@Transactional(value=“chainedTransactionManager”),这样spring就可以处理这个问题。

相关问题