Spring @Transactional with a transaction across multiple data sources

前端 未结 4 1430
终归单人心
终归单人心 2020-12-05 01:18

I have to update two data sources as part of one transaction. That is -

  1. I do an update in DB1.
  2. Then, I do another update in DB2.

If upd

4条回答
  •  长情又很酷
    2020-12-05 01:53

    I've solved this problem using ChainedTransactionManager - http://docs.spring.io/spring-data/commons/docs/1.6.2.RELEASE/api/org/springframework/data/transaction/ChainedTransactionManager.html

    Spring Boot Configuration:

        @Bean(name = "chainedTransactionManager")
        public ChainedTransactionManager transactionManager(@Qualifier("primaryDs") PlatformTransactionManager ds1,
                                                        @Qualifier("secondaryDs") PlatformTransactionManager ds2) {
             return new ChainedTransactionManager(ds1, ds2);
        }
    

    And then you can use it as follows:

    @Transactional(value="chainedTransactionManager")
    public void updateDb01() {
        Entity01 entity01 = repository01.findOne(1234);
        entity01.setName("Name");
        repository01.save(entity01);
    
        //Calling method to update DB02
        updateDb02();
    }
    
    public void updateDb02() {
        Entity02 entity02 = repository02.findOne(1234);
        entity02.setName("Name");
        repository02.save(entity02);
    
        //Added this to force a roll back for testing
        TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
    }
    

提交回复
热议问题