0

I have a method annotated with @Transactional that calls a second method annotated with @Transactional(propagation=Propagation.REQUIRES_NEW), which in turn calls a third method annotated with @Transactional. If the third method throws an exception and it is caught and suppressed in the second method, the transaction from the first method will be rolled back. However, if the third method does not have the @Transactional annotation, only the transaction from the second method will be rolled back. Why @Transactional affect on transaction from first method instead of new transaction from second?

@Service
class FirstClass {

    private final SecondClass secondClass;

    @Transactional
    public void firstMethod() {
        //... some code
        secondClass.secondMethod();
        //... some code
    }
}

@Service
class SecondClass {

    private final ThirdClass thirdClass;


    @Transactional(Propagation.REQUIRES_NEW)
    public void secondMethod() {
        //... some code
        try {
            thirdClass.thirdMethod();
            //... some code
        }catch (Exception e){

        }
    }
}

@Service
class ThirdClass {

    @Transactional // this transaction 
    public void thirdMethod() {
        throw new RuntimeException();
    }

}

if we rewrite third method by this way:

@Service
class ThirdClass {

    public void thirdMethod() {
        throw new RuntimeException();
    }

}

In this scenario, the first transaction will not be rolled back.

Marek Puchalski
  • 3,286
  • 2
  • 26
  • 35

0 Answers0