Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring @Transactional annotation when using try catch block

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     } } 
like image 247
Kedar Parikh Avatar asked Sep 09 '14 07:09

Kedar Parikh


People also ask

On which can be @transactional annotation be applied?

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.

Does @transactional work on protected methods?

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.

Is it sufficient to annotate the classes with the @transactional annotation?

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.

Is @transactional required in Spring boot?

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.


1 Answers

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.

like image 136
Ankur Singhal Avatar answered Sep 21 '22 16:09

Ankur Singhal