Spring Transaction Management-rollback (rollback-for) control _spring

Source: Internet
Author: User
Tags aop rollback throw exception

In spring transaction control, the principle of exception trigger transaction rollback is discussed. The article has 6 scenarios in which spring transactions are rolled back.
The following code is based on spring-and-mybatis consolidation, using the Spring declarative transaction to configure the transaction method. 1. Do not catch exceptions (general processing mode)

Code, wherein Contentmappger.updatewitherrtest (31L); is an SQL statement error that is used to test the rollback.

    /**
     * Delete multiple records *
     *
    @Override public
    shopresult deletecontentgroup (string[] IDs) {
        if (null = ids | | Ids.length = = 0)
        {return
            shopresult.error ();
        }
        for (String idstr:ids)
        {
            Long id = new Long (IDSTR);
            Contentmappger.deletebyprimarykey (ID);
        }
        Contentmappger.updatewitherrtest (31L);   Error code, SQL statement error. Used to test transactions to see if rollback return
        Shopresult.ok ();
    }

Run Result: An error occurred, the transaction was rolled back, that is, the previous for loop delete record transaction was rolled back because of a fault code.

### sql:delete form tb_content where kid =? ### Cause:com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException:You have a error in your SQL syntax; Check the manual that corresponds to your MySQL server version for the right syntax to use near ' tb_content where kid = ' at line 1; Bad SQL Grammar []; Nested exception is Com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException:You have a error in your SQL syntax; Check the manual that corresponds to your MySQL server version for the right syntax to use near ' tb_content where kid = To ' at line 1] with root cause com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException:You have a error in your SQL Syntax Check the manual that corresponds to your MySQL server version for the right syntax to use near ' tb_content where kid = To ' at line 1 at Sun.reflect.NativeCons Sun.reflect.NativeConstructorAccessorImpl.newInstance0 (Native method) Tructoraccessorimpl.newinstance (nativeconstructoraccessorimpl.java:62)
    At Sun.reflect.DelegatingConstructorAccessorImpl.newInstance (delegatingconstructoraccessorimpl.java:45) at JAVA.L Ang.reflect.Constructor.newInstance (constructor.java:423) at Com.mysql.jdbc.Util.handleNewInstance (util.java:406 ) at Com.mysql.jdbc.Util.getInstance (util.java:381) at Com.mysql.jdbc.SQLError.createSQLException (sqlerror.java:10 At Com.mysql.jdbc.SQLError.createSQLException (sqlerror.java:956) in Com.mysql.jdbc.MysqlIO.checkErrorPacket (my sqlio.java:3536) at Com.mysql.jdbc.MysqlIO.checkErrorPacket (mysqlio.java:3468) at Com.mysql.jdbc.MysqlIO.sendComma
    nd (mysqlio.java:1957) ... org.apache.ibatis.binding.MapperProxy.invoke (mapperproxy.java:53). At the (). At the At Com.sun.proxy. $Proxy 35.updateWithErrTest (Unknown Source) at Com.shop.manager.service.impl.ContentServiceImpl.deleteContentGroup (contentserviceimpl.java:94) at Sun.reflect.NativeMethodAccessorImpl.invoke0 (Native method) at Sun.reflect.NativeMethodAccessorImpl.Invoke (nativemethodaccessorimpl.java:62) at Sun.reflect.DelegatingMethodAccessorImpl.invoke ( delegatingmethodaccessorimpl.java:43) at Java.lang.reflect.Method.invoke (method.java:498) at org.springframework.a Op.support.AopUtils.invokeJoinpointUsingReflection (aoputils.java:302) at Org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint (Reflectivemethodinvocation.java : 190).
2. Catch exception, but do not handle, do not throw

Code

    /**
     * Delete multiple records *
     *
    @Override public
    shopresult deletecontentgroup (string[] IDs) {
        if (null = ids | | Ids.length = = 0)
        {return
            shopresult.error ();
        }
        for (String idstr:ids)
        {
            Long id = new Long (IDSTR);
            Contentmappger.deletebyprimarykey (ID);
        }
        try {
            contentmappger.updatewitherrtest (31L);   Error code, SQL statement error. Used to test the transaction to see if the rollback
        } catch (Exception e) {
            //catches the exception, but does not handle
            System.out.println ("-----Nothing todo-------");
        } return
        Shopresult.ok ();
    }

Run Result: Transaction commits, not rolled back.

### The error occurred while setting parameters
### sql:delete form tb_content    where kid =?
### Cause:com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException:You have a error in your SQL syntax; Check the manual that corresponds to your MySQL server version for the right syntax to use near ' tb_content
    where kid = ' at line 1]-----No to do
-------
2017-06-18 14:27:59,493 [http-bio-8080-exec-4] [ Org.mybatis.spring.sqlsessionutils]-[debug] Transaction Synchronization committing sqlsession//(transaction submission)
[ ORG.APACHE.IBATIS.SESSION.DEFAULTS.DEFAULTSQLSESSION@616A85A9]
3. Catch exception and throw RuntimeException exception

Spring Encounters unchecked exceptions will roll back, not only runtimeexception, but also error.
Code

    /**
     * Delete multiple records *
     *
    @Override public
    shopresult deletecontentgroup (string[] IDs) {
        if (null = ids | | Ids.length = = 0)
        {return
            shopresult.error ();
        }
        for (String idstr:ids)
        {
            Long id = new Long (IDSTR);
            Contentmappger.deletebyprimarykey (ID);
        }
        try {
            contentmappger.updatewitherrtest (31L);   Error code, SQL statement error. Used to test transactions to see if rollback
        } catch (Exception e) {
            System.out.println ("----Throw Exception-----");
            throw new RuntimeException ();
        }
        return Shopresult.ok ();
    }

Run result: As expected, throw runtimeexception, the transaction occurs rollback.

### sql:delete form tb_content where kid =? ### Cause:com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException:You have a error in your SQL syntax; Check the manual that corresponds to your MySQL server version for the right syntax to use near ' tb_content where kid = To ' at line 1]----throw Exception-----2017-06-18 14:21:27,928 [http-bio-8080-exec-1] [Org.mybatis.spring.SqlSessionU Tils]-[debug] Transaction synchronization deregistering sqlsession [
ORG.APACHE.IBATIS.SESSION.DEFAULTS.DEFAULTSQLSESSION@3EF56E3A] ......... 2017-06-18 14:21:27,941 [Http-bio-8080-exec-1] [ Org.springframework.web.servlet.mvc.method.annotation.exceptionhandlerexceptionresolver]-[debug] Resolving Exception from handler [public Com.shop.common.pojo.ShopResult
Com.shop.manager.controller.ContentController.deleteContentGroup (java.lang.String)]: java.lang.RuntimeException 2017-06-18 14:21:27,941 [Http-bio-8080-exec-1] [ Org.springframework.web.servlet.mvc.annotation.ResponseStatusExceptionResolVer]-[debug] Resolving exception from handler [public Com.shop.common.pojo.ShopResult
Com.shop.manager.controller.ContentController.deleteContentGroup (java.lang.String)]: java.lang.RuntimeException 2017-06-18 14:21:27,942 [Http-bio-8080-exec-1] [ Org.springframework.web.servlet.mvc.support.defaulthandlerexceptionresolver]-[debug] Resolving exception from handler [public Com.shop.common.pojo.ShopResult Com.shop.manager.controller.ContentController.deleteContentGroup ( java.lang.String)]: java.lang.RuntimeException 2017-06-18 14:21:27,942 [Http-bio-8080-exec-1] [ Org.springframework.web.servlet.dispatcherservlet]-[debug] Could not complete request java.lang.RuntimeException at C Om.shop.manager.service.impl.ContentServiceImpl.deleteContentGroup (contentserviceimpl.java:98)//exception at Sun.reflect.NativeMethodAccessorImpl.invoke0 (Native method)
4. Catch the exception and continue throwing the original caught exception

Code:

    /**
     * Delete multiple records *
     *
    @Override public
    shopresult deletecontentgroup (string[] IDs) {
        if (null = ids | | Ids.length = = 0)
        {return
            shopresult.error ();
        }
        for (String idstr:ids)
        {
            Long id = new Long (IDSTR);
            Contentmappger.deletebyprimarykey (ID);
        }
        try {
            contentmappger.updatewitherrtest (31L);   Error code, SQL statement error. Used to test transactions, see if Rollback
        } catch (Exception e) {
            //catch exception, continue to throw
            System.out.println ("-----throw Exception-------");
            throw e;
        }
        return Shopresult.ok ();
    }

Run Result: Throws an exception, the transaction happens to roll back

### The error occurred while setting parameters
### sql:delete form tb_content    where kid =?
### Cause:com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException:You have a error in your SQL syntax; Check the manual that corresponds to your MySQL server version for the right syntax to use near ' tb_content
    where kid = To ' at line 1
]
-----Throw Exception-------
2017-06-18 14:36:25,308 [http-bio-8080-exec-9] [ Org.mybatis.spring.sqlsessionutils]-[debug] Transaction synchronization deregistering sqlsession [ ORG.APACHE.IBATIS.SESSION.DEFAULTS.DEFAULTSQLSESSION@45FE0F70]
2017-06-18 14:36:25,308 [http-bio-8080-exec-9 ] [Org.mybatis.spring.sqlsessionutils]-[debug] Transaction synchronization closing sqlsession//transaction rollback
[ ORG.APACHE.IBATIS.SESSION.DEFAULTS.DEFAULTSQLSESSION@45FE0F70]
5. Catch the exception, and throw the exception (or custom Exception exception) of the new a Exception

Code:

    /**
     * Delete multiple records
     * @throws Exception * * * 
     @Override public
    shopresult deletecontentgroup (string[) IDs) Throws Exception {
        if (null = = IDs | | ids.length = 0)
        {return
            shopresult.error ();
        }
        for (String idstr:ids)
        {
            Long id = new Long (IDSTR);
            Contentmappger.deletebyprimarykey (ID);
        }
        try {
            contentmappger.updatewitherrtest (31L);   Error code, SQL statement error. Used to test the transaction to see if the rollback
        } catch (Exception e) {
            //catches the exception, throws a new exception
            System.out.println ("-----throw new Exception (e)---- ---");
            throw new Exception (e);
        }       
        return Shopresult.ok ();
    }

Run Result: Transaction commits, not rolled back. (The default rollback exception type for spring does not include exception)

### The error occurred while setting parameters
### sql:delete form tb_content    where kid =?
### Cause:com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException:You have a error in your SQL syntax; Check the manual that corresponds to your MySQL server version for the right syntax to use near ' tb_content
    where kid = To ' at line 1
]
-----throw new Exception (e)-------
2017-06-18 14:43:16,098 [http-bio-8080-exec-10] [ Org.mybatis.spring.sqlsessionutils]-[debug] Transaction Synchronization committing sqlsession//transaction Submission
[ ORG.APACHE.IBATIS.SESSION.DEFAULTS.DEFAULTSQLSESSION@32C4821]
2017-06-18 14:43:16,098 [http-bio-8080-exec-10 ] [Org.mybatis.spring.sqlsessionutils]-[debug] Transaction synchronization deregistering sqlsession [ ORG.APACHE.IBATIS.SESSION.DEFAULTS.DEFAULTSQLSESSION@32C4821]
6. The rollback-for exception type is not set in the transaction configuration exception
<!--transaction manager--> <bean id= "TransactionManager" class= " Org.springframework.jdbc.datasource.DataSourceTransactionManager "> <property name=" DataSource "ref=" Datasou Rce "/> </bean> <!--notification--> <tx:advice id=" Txadvice "transaction-manager=" TransactionManager "> <!--transaction behavior Control--> <tx:attributes> <tx:method name=" Save "propagation=" Requi RED "rollback-for=" Exception "/> <tx:method name=" insert* "propagation=" REQUIRED "rollback-for=" exceptio N "/> <tx:method name= add*" propagation= "REQUIRED" rollback-for= "Exception"/> <tx:met Hod name= "create*" propagation= "REQUIRED" rollback-for= "Exception"/> <tx:method "name=" delete* ion= "REQUIRED" rollback-for= "Exception"/> <tx:method name= "update*" propagation= "REQUIRED" Rollback-fo R= "Exception"/> <tx:method name= "find*" propagation= "SUPPORTS" REad-only= "true"/> <tx:method name= "select*" propagation= "SUPPORTS" read-only= "true"/> & Lt;tx:method name= "get*" propagation= "SUPPORTS" read-only= "true"/> </tx:attributes> &LT;/TX:ADVICE&G
    T <!--configuration Slice--> <aop:config> <aop:advisor advice-ref= "Txadvice" pointcut= Execution (* com.shop.ma Nager.service.*.* (..)) " /> </aop:config>
    /**
     * Delete multiple records
     * @throws Exception * * * 
     @Override public
    shopresult deletecontentgroup (string[) IDs) Throws Exception {
        if (null = = IDs | | ids.length = 0)
        {return
            shopresult.error ();
        }
        for (String idstr:ids)
        {
            Long id = new Long (IDSTR);
            Contentmappger.deletebyprimarykey (ID);
        }
        try {
            contentmappger.updatewitherrtest (31L);   Error code, SQL statement error. Used to test the transaction, see if Rollback
        } catch (Exception e) {
            //catch exception, continue to throw
            System.out.println ("-----throw new Exception-------" );
            throw new Exception ("---custom Exception, rollback-for---" configured in transaction);
        }
        return Shopresult.ok ();
    }

Run Result: rollback occurs as expected

 ### The error may involve Com.shop.manager.mapper.tbcontentmapper.updatewitherrtest-inline ### the error occurred
While setting parameters ### sql:delete form tb_content where kid =? ### Cause:com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException:You have a error in your SQL syntax; Check the manual that corresponds to your MySQL server version for the right syntax to use near ' tb_content where kid = To ' at line 1]-----throw new Exception-------2017-06-18 15:07:02,273 [http-bio-8080-exec-8] [org.mybatis.spring.SqlSe Ssionutils]-[debug] Transaction synchronization deregistering sqlsession [ ORG.APACHE.IBATIS.SESSION.DEFAULTS.DEFAULTSQLSESSION@F177061] 2017-06-18 15:07:02,273 [http-bio-8080-exec-8] [ Org.mybatis.spring.sqlsessionutils]-[debug] Transaction synchronization closing sqlsession [ ORG.APACHE.IBATIS.SESSION.DEFAULTS.DEFAULTSQLSESSION@F177061] 
Summary: Spring transaction management is a rollback operation based on an exception; When spring is consolidated with MyBatis, there is no check exception in the service method, but if the database has an exception, the transaction is rolled back by default. Spring If you do not add attributes such as Rollbackfor, Spring encounters unchecked exceptions will roll back, not only runtimeexception, but also error. If you catch exceptions and process them in a transaction method, be sure to continue throwing exceptions and rollbak-for configuration in spring transaction management.

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.