Search code examples
javaspringtransactionsrollbackunchecked-exception

Should @Transactional method roll back in case of calling a private method which throws RuntimeException in Spring?


Should transaction rolled back here?

@Service
public class Serv {
    @Transactional
    public void method1() {
        method2();
    }
    private void method2(){
        throw new RuntimeException();
    }
}

Or does it depend on something?

( Before today I was 100% sure in the described behavior. But an interviewer said it depends. I disagreed with him but of course it doesn't help.)


Solution

  • The optimal/usual result is rollback as you answered, but interviewer said general statement as it depends

    Maybe the interviewer meant to check if you know when it won't rollback as expected

    Meaning that you shouldn't assume @Transactional is actually working, it should be checked first, because if @Transactional isn't working there'll be no rollback.

    For example, in case of calling transactional method in same class, if method1() is called from method3() in same class @Transactional won't work and won't rollback