If we catch the exception in method annotated with the @Transactional
annotation, will it roll back if any exception occurs?
@Transactional(readOnly = false, propagation = Propagation.REQUIRED, rollbackFor=Throwable.class) public void yearEndProcess() { try { // try block } catch (Throwable throwable) { // catch block } }
The @Transactional annotation makes use of the attributes rollbackFor or rollbackForClassName to rollback the transactions, and the attributes noRollbackFor or noRollbackForClassName to avoid rollback on listed exceptions. The default rollback behavior in the declarative approach will rollback on runtime exceptions.
When using proxies, you should apply the @Transactional annotation only to methods with public visibility. If you do annotate protected, private or package-visible methods with the @Transactional annotation, no error is raised, but the annotated method does not exhibit the configured transactional settings.
It is not sufficient to tell you simply to annotate your classes with the @Transactional annotation, add the line ( <tx:annotation-driven/> ) to your configuration, and then expect you to understand how it all works.
However, if we put the annotation on a private or protected method, Spring will ignore it without an error. Usually it's not recommended to set @Transactional on the interface; however, it is acceptable for cases like @Repository with Spring Data.
for example
class A{ @Transactional public Result doStuff(){ Result res = null; try { // do stuff } catch (Exception e) { } return res ; } }
If there is an exception in the method doStuff
the transaction isn't rolled back.
To rollback the exception programmatically
, we can do something like below.
declarative approach
@Transactional(rollbackFor={MyException1.class, MyException2.class, ....}) public Result doStuff(){ ... }
programmatic rollback
you need to call it from TransactionAspectSupport
.
public Result doStuff(){ try { // business logic... } catch (Exception ex) { // trigger rollback programmatically TransactionAspectSupport.currentTransactionStatus().setRollbackOnly(); } }
You are strongly encouraged to use the declarative approach
to rollback
if at all possible. Programmatic rollback
is available should only be used if you absolutely need it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With