交易中的Spring程序化交易 [英] Spring Programmatic transaction within transaction

查看:78
本文介绍了交易中的Spring程序化交易的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在下面的活动中编写了以下代码 我使用Spring类创建了一个事务. 插入了一行. 创建了其他交易. 插入另一行. 承诺的外部交易. 回滚内部事务.

I have written below code doing below activities I created one transaction using Spring classes. Inserted one row. Created other transaction. Inserted another row. committed outer transaction. Rolledback inner transaction.

TransactionStatus trxstsOuter= dsTrxMngr.getTransaction(null);
    jdbcTemplate.update("insert into kau_emp values(6,'xyz' )");
    TransactionStatus trxstsInner= dsTrxMngr.getTransaction(null);
        jdbcTemplate.update("insert into kau_emp values(7,'pqr' )");

dsTrxMngr.commit(trxstsOuter);
System.out.println("trxstsOuter.isCompleted()" + trxstsOuter.isCompleted());
System.out.println("trxstsInner.isCompleted()" + trxstsInner.isCompleted());
dsTrxMngr.rollback(trxstsInner);
    System.out.println("trxstsInner.isCompleted()" + trxstsInner.isCompleted());

我观察到这两行都提交给DB! 输出是

I observed that both the rows are committed to DB !! The output is

trxstsOuter.isCompleted()true
trxstsInner.isCompleted()false
trxstsInner.isCompleted()true

这是正确的行为吗? 在允许外部事务提交之前,内部事务是否不应该首先提交/回滚? 如果外部事务已提交,内部回滚是否应该抛出错误?

Is it correct behavior ? Should not inner transaction be first committed/rollbacked before allowing outer transaction to commit ? If outer transaction was committed, should rollback of inner thrown an error ?

推荐答案

在您的示例中,事务Propagation.REQUIRED被用作默认值,并且所有逻辑事务都映射到单个物理事务

In your example transaction Propagation.REQUIRED is used as the default value, and all the logic transactions are mapped to the single physical transaction

当传播设置为PROPAGATION_REQUIRED时, 将为设置所基于的每个方法创建事务范围 应用.每个这样的逻辑事务范围可以确定 具有外部事务范围的单独回滚状态 在逻辑上独立于内部交易范围.的 当然,在标准的PROPAGATION_REQUIRED行为的情况下,所有这些 范围将映射到相同的物理事务.所以一个 内部事务范围中设置的仅回滚标记确实会影响 外部交易实际落实的机会(正如您所期望的那样 来).

When the propagation setting is PROPAGATION_REQUIRED, a logical transaction scope is created for each method upon which the setting is applied. Each such logical transaction scope can determine rollback-only status individually, with an outer transaction scope being logically independent from the inner transaction scope. Of course, in case of standard PROPAGATION_REQUIRED behavior, all these scopes will be mapped to the same physical transaction. So a rollback-only marker set in the inner transaction scope does affect the outer transaction's chance to actually commit (as you would expect it to).

因此,在您的示例中,两个逻辑事务被映射到一个物理事务.

So in your example two logical transactions are mapped to one physical transaction.

请参见 查看全文

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