Spring transaction exception rollback, catch exception not thrown will not be rolled back (reprinted) solved the problem I had a year ago.

Source: Internet
Author: User
Tags try catch

I have recently encountered a transaction not rollback, I also consider that the JPA transaction has a bug? I think more ...
In order to print clear logs, many methods I add Tyr catch to print the log in the catch. But the situation here, when this method is abnormal when the log is printed, but the addition of the transaction has not been rolled back.

Example:
A method like this does not roll back (one method fails and the other does not):

if (usersave) {            try  {               userdao.save (user);                Usercapabilityquotadao.save (Capabilityquota);             Catch (Exception e) {                logger.info ("ability to open Interface, account opening exception, exception information:" +e);            }        }

The following method is rolled back (one method error and another method is rolled back):

if (usersave) {              try  {                  userdao.save (user);                  Usercapabilityquotadao.save (Capabilityquota);                 Catch (Exception e) {                 logger.info ("ability to open Interface, account opening exception, exception information:" +e                  ); Throw New runtimeexception ();              }          }

Or:

 if   (Usersave) { try   {userdao.save (user);              Usercapabilityquotadao.save (Capabilityquota);  catch   (Exception e) {logger.                  Info ( "Ability to open Interface, account opening exception, exception information:" +e);             Transactionaspectsupport.currenttransactionstatus (). Setrollbackonly (); }          }  

Why don't you roll?? It is not clear to spring's transaction mechanism.!!
The default spring transaction is rolled back only when an uncaught runtimeexcetpion 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, but can be

Configuration to catch a specific exception and roll back
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.
Solution:
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. And on the service upper level (WebService client, view layer action) to continue catching this exception and handling
Scenario 2. Add: Transactionaspectsupport.currenttransactionstatus (). Setrollbackonly () in the catch statement of the service layer method; statement, manual rollback, So that the upper layer does not have to deal with the exception (now the project practice)

Reference blog Spring transaction management only rolls back http://blog.csdn.net/abc19900828/article/details/39497631 when a run-time exception occurs

Spring thing propagation mechanism and isolation level http://blog.csdn.net/hijiankang/article/details/9174461

Spring Transaction Detailed http://blog.csdn.net/u013628152/article/details/47980811

1:java contains two types of exceptions: checked and unchecked exceptions.

The difference between checked and unchecked exceptions is:
Checked exceptions must be explicitly captured try-catch-finally, while unchecked exceptions can not be captured or thrown.
The checked exception inherits the Java.lang.Exception class. The unchecked exception inherits from the Java.lang.RuntimeException class.

Main differences between InnoDB and MyISAM in the 2:mysql storage engine

Transactional aspects: InnoDB supports transactional functions, MyISAM not supported.
Myisam executes faster and performs better.

Engine = InnoDB and engine = MyISAM
You can use one of the following statements to check a table's table type:
SHOW TABLE STATUS like ' tbl_name ';
SHOW CREATE TABLE tbl_name;

Use the following statement to check the storage engines supported by the MYSQLD server:
SHOW ENGINES;

3:spring Transaction Processing

throw new RuntimeException ("xxxxxxxxxxxx"); Default transaction rollback
throw new Exception ("xxxxxxxxxxxx"); Default transaction does not roll back
Spring's AOP, declarative transaction management, is the default for unchecked exception rollback. The default is to RuntimeException () exception or its subclass for transaction rollback;
Checked exception, throw new exception does not roll back by default

If you want to have checked exceptions or a custom exception rollback
(1) configuration file mode

<Tx:adviceId="Txadvice" ><Tx:attributes><Tx:methodName="Update*"No-rollback-for="IOException"/><Tx:methodName="*"/></tx:attributes> </tx:advice><tx:advice id="Txadvice"  transaction-manager="TransactionManager" > <tx:attributes> <tx:method  Name="*" rollback-for="com.cn.untils.exception.MyException"/> </tx:attributes> </tx:advice>                

(2) How to annotate

@Transactional(rollbackFor = Exception.class) @Transactional(rollbackFor = MyException.class)

does not work:

@Transactionalpublic void addAdmin(Admin admin) throws Exception { try { this.adminDao.add(admin); admin.setUsername("123456789012345"); this.adminDao.update(admin); } catch (Exception e) { e.printStackTrace(); throw new Exception("测试!"); }}

Work

@Transactional(rollbackFor = Exception.class)public void addAdmin(Admin admin) throws Exception { try { this.adminDao.add(admin); admin.setUsername("123456789012345"); this.adminDao.update(admin); } catch (Exception e) { e.printStackTrace(); throw new Exception("测试!"); }}
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12

Work

@Transactionalpublic void addAdmin(Admin admin) {    try { this.adminDao.add(admin); admin.setUsername("123456789012345"); this.adminDao.update(admin); } catch (Exception e) { e.printStackTrace(); throw new RuntimeException("测试!"); }}

Complete wording:

@Transactional(rollbackFor = RuntimeException.class)public void addAdmin(Admin admin) {    try { this.adminDao.add(admin); admin.setUsername("123456789012345"); this.adminDao.update(admin); } catch (Exception e) { e.printStackTrace(); throw new RuntimeException("测试!"); }

Spring transaction exception rollback, catch exception not thrown will not be rolled back (reprinted) solved the problem I had a year ago.

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.