Spring @Transactional with a transaction across multiple data sources

前端 未结 4 1434
终归单人心
终归单人心 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:43

    The best way is to create a third method, that will be annotated as @Transactional.

    @Transactional(readOnly = false)
    public void updateCommon(){
      upbateDb01();
      upbateDb02();
    }
    

    According to a spring documentation, transaction control starts when the firts annotation appears,so in this case a single transaction will start when updateCommon will be invoked. UPDATE But this will work if you use CrudRepository or something like that.

    In case of multiple datasources you may try to use a Global transaction management conception. Here is a sample from a spring documentation:

    @Inject private PlatformTransactionManager txManager; 
    
    TransactionTemplate template  = new TransactionTemplate(this.txManager); 
    template.execute( new TransactionCallback(){ 
      public void doInTransaction(TransactionStatus status){ 
       // work done here will be wrapped by a transaction and committed. 
       // the transaction will be rolled back if 
       // status.setRollbackOnly(true) is called or an exception is thrown 
      } 
    });
    
    
    

    And here is a link: http://spring.io/blog/2011/08/15/configuring-spring-and-jta-without-full-java-ee/ I have never use it for my own, so I didn't explore this topic deeply. Hope it will help

    提交回复
    热议问题