简体   繁体   English

异常后未持久保存JPA实体

[英]JPA Entity is not being persisted after exception

I´m having the following problem: 我遇到以下问题:

I have 2 classes (A and B). 我有2节课(A和B)。 The class A has a method (method1) annotated with @Transaction(noRollBackFor = ExceptionB.class) that calls the method2 from class B. ExceptionB is a non-checked RunTimeException. 类A有一个用@Transaction(noRollBackFor = ExceptionB.class) )注释的方法(method1),它从类B调用@Transaction(noRollBackFor = ExceptionB.class)是未经检查的RunTimeException。

public class A {
    ...

    @Resource
    private B b;

    @Transaction(noRollBackFor = ExceptionB.class)
    public void method1() {

      try {
            b.method2();
      } catch (ExceptionB e) {
            // Change objects annotated with @Entity (must be persisted)
            throw e;
      }

    }
}

@Transaction
public class B {
    ...

    public void method2() {
            ...
            throw new ExceptionB();
    }
}

However, when the class B throws the exception, a Spring Interceptor gets the exception and uses the class B transaction annotation rules (that don´t have the noRollBackFor rule) and do the transaction rollback. 但是,当类B引发异常时,Spring Interceptor会获取异常并使用类B事务注释规则(不具有noRollBackFor规则)并执行事务回滚。 In this way, all the changes done in method1 aren´t persisted. 这样,方法1中所做的所有更改都不会保留。 What should I change to the rollback doesn´t happen? 我应该更改为未发生回滚?

Thank you in advance. 先感谢您。

Well, I´ve already solved my issue. 好吧,我已经解决了我的问题。 The point is that the class B was annotated by @Transaction, so for each public method called (such as method2) a new transaction was created without a noRollBack property. 关键是类B由@Transaction注释,因此对于每个称为(例如method2)的公共方法,将创建一个没有noRollBack属性的新事务。 In this way, for my case, the solution is take out the @Transaction annotation from the class and add it only to the methods that need a new transaction, ie, method2 is with no annotations. 以这种方式,对于我来说,解决方案是从类中删除@Transaction注释,并将其仅添加到需要新事务的方法中,即method2没有注释。

That´s all! 就这样!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM