Spring @Transactional具有跨多个数据源的事务 [英] Spring @Transactional with a transaction across multiple data sources

查看:1546
本文介绍了Spring @Transactional具有跨多个数据源的事务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

作为一项交易,我必须更新两个数据源.那是-

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

  1. 我在DB1中进行更新.
  2. 然后,我在DB2中进行另一个更新.

如果DB2中的更新失败,我想回滚DB1和DB2来回滚.可以使用@Transactional完成此操作吗?

If update in DB2 fails, I want to roll back both DB1 and DB2 to roll back. Can this be accomplished using @Transactional ?

这是示例代码-

@Transactional(value="db01TransactionManager")
public void updateDb01() {
    Entity01 entity01 = repository01.findOne(1234);
    entity01.setName("Name");
    repository01.save(entity01);

    //Calling method to update DB02
    updateDb02();
}

@Transactional(value="db02TransactionManager")
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();
}

我的问题是,updateDb02中的setRollbackOnly()仅回滚Db01事务.

My problem is that, the setRollbackOnly() in updateDb02 rolls back only the the Db01 transaction.

推荐答案

我已经使用ChainedTransactionManager解决了这个问题-

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配置:

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();
}

这篇关于Spring @Transactional具有跨多个数据源的事务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆