EJB:避免事务回滚 [英] EJB: Avoid Transaction rollback

查看:261
本文介绍了EJB:避免事务回滚的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当EJB的(事务)方法调用另一个EJB的另一个(事务性)方法,并且在第二个中抛出异常,但在第一个中抛出异常时,似乎事务在第二个时自动回滚一个人回来,即使第一个人抓住它,这是真的吗?我该如何避免呢?

When a (transactional) method of an EJB calls another (transactional) method of another EJB, and an exception is thrown in the second, but catched in the first one, it seems that the transaction is automatically rolled back when the second one returns, even if the first one catches it, is this true? how can I avoid it?

场景如下:

@Stateless
class ClassA {
   @EJB
   ClassB objectB;

   methodA() { 
       try { 
            objectB.methodB(); 
       }
       catch(Exception e) {
            //Here the transaction started in this method is 
            //automatically rolled back. Is this avoidable?
       } 
   }
}

@Stateless
class ClassB {
   methodB() throws Exception { throw new Exception() }
}


推荐答案

如果您抛出,将回滚交易a RuntimeException 或任何具有 @ApplicationException 注释的异常回滚属性设置为 true ,所以:

Transaction is rolled back in case you throw a RuntimeException or any Exception which have @ApplicationException annotation with rollback attribute set to true, so:

@ApplicationException(rollback=true)
public class MyException extends Exception {
    // ...
}

将回滚当前事务。

默认情况下,ApplicationException不会回滚您的事务。

By default ApplicationException doesn't rollback your transaction.

如果您不希望使用methodB来回滚事务,则可以更改 ApplicationException 的回滚行为,或者阻止事务共享。

If you don't want to methodB to rollback your transaction you can either change the rollback behavior of your ApplicationException or prevent the transaction sharing.

后者可通过更改 Transactio来实现nAtttribute方法B的,即 RequiresNew 。然后methodA transaction(Tx1)将是suspendend,并且如果methodB抛出一个导致其事务回滚(Tx2)的异常,你仍然可以在methodA中捕获它并阻止回滚methodA事务(Tx1)。

The latter is achievable by changing the TransactionAttribute of methodB i.e. to RequiresNew. Then methodA transaction (Tx1) will be suspendend and in case methodB throws an exception which results in rollback of its transaction (Tx2), you can still catch it in methodA and prevent rollback of your methodA transaction (Tx1).

这篇关于EJB:避免事务回滚的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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