Spring Boot @Transactional No rollback workaround

Source: Internet
Author: User
Tags try catch

When a compile-time exception is thrown, the transaction does not roll back, and the employee successfully inserts the data.

1 @Transactional2      PublicEmployee Saveemployee ()throwsException {3Employee Employee =NewEmployee ();4Employee.setname ("ZZ");5Employee.setage (60);6 Employeemapper.insert (employee);7         8         if(Employee.getage () = = 60) {9             Throw NewException ("Age = 60");Ten         } One  ASalary Salary =NewSalary (); -Salary.setsalary (60); - Salarymapper.insert (salary); the  -         returnemployee; -}


The default spring transaction is rolled back only when an uncaught runtimeexception occurs.

Spring AOP Exception Trapping principle: The method being intercepted explicitly throws an exception and cannot be processed so that the AOP agent catches the exception of the method before it can be rolled back, and AOP catches only runtimeexception exceptions by default. However, a specific exception can be captured and rolled back by configuration

In other words, no try catch is used in the service's method or a throw new Runtimeexcetpion () is finally added to the catch, so that the program can be caught by AOP and then rolled back.


Scenario 1. For example, the service layer processes the transaction, then no exception is caught in the methods in the service, or the throw new RuntimeException () statement is finally added to the catch statement so that AOP catches the exception and then rolls back.

Scenario 2. Add: Transactionaspectsupport.currenttransactionstatus (). Setrollbackonly () in the catch statement of the service layer method; statement, manual rollback, This way the upper layer does not have to deal with exceptions.



Spring Boot @Transactional No rollback workaround

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.