简体   繁体   中英

JPA Entity is not being persisted after exception

I´m having the following problem:

I have 2 classes (A and 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.

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. In this way, all the changes done in method1 aren´t persisted. 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. 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.

That´s all!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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