Search code examples
javaspringtransactional

PROPAGATION_REQUIRED behavior in spring?


I have few questions on PROPAGATION_REQUIRED behaviour which i am not able to clarify on Spring Docs.

Scenario1:-

@Transactional
method1(){
// do some update without exception
}

Data will be committed as thread comes out of method1. Right ?

Scenario2:-

@Transactional
method1(){
// do some update without exception
method2();
}

@Transactional
method2(){
// do some update without exception
}

Data will be committed as thread comes out of method1. Right ?

Scenario3:-

@Transactional
method1(){
// do some update without exception
method2();
}

@Transactional
method2(){
 // some update in DB 
 throw new RunTimeException()
}

Nothing will be commited. Right ?

Scenario4:-

@Transactional
method1(){
// do some update without exception
method2();
}

@Transactional
method2(){
 // some update in DB 
 throw new SomeCheckedException()
}

whole transaction will be committed as thread comes out of method1 as checked exception is thrown. Though i could change this behaviour with @Transactional(rollbackFor=SomeCheckedException.class) Right ?

Please let me know if above understanding is correct.


Solution

  • Yes, checked exceptions don't automatically rollback the active transaction; only unchecked RuntimeException do.

    If you want rollback for certain checked exceptions, you can use @Transactional(rollbackFor=SomeCheckedException.class)

    Note: @Transactional has no effect when you call the method internally:

    method1(){
      method2();
    }
    
    @Transactional
    method2(){
      // some update in DB -> fails because there is no transaction
    }
    

    The annotation can only be applied when Spring can wrap the method call.