Spring transaction rollback, spring transaction

Source: Internet
Author: User

Spring transaction rollback, spring transaction

1. Problems Encountered

When there are multiple database storage operations in one method, database operations in the middle are incorrect. The pseudocode is as follows:

Public method () {Dao1.save (Person1); Dao1.save (Person2); Dao1.save (Person2); // if an error occurs, the first two objects will be saved to the database Dao1.save (Person2 );}

Expected situation: Before an error occursRoll back all database save operations, That is, do not save

Normal situation: the previous database operation will be executed, and the database operation error starts and all subsequent data saving operations will fail. This should not be the result we want.

In this case, we can use Spring transactions to solve this problem.

2. Basic abnormal knowledge

1) abnormal Architecture

Exception inheritance structure: Throwable is the base class. Error and Exception inherit Throwable, RuntimeException, and IOException. Error, RuntimeException, and its subclass become unchecked, and other exceptions become checked ).

2) Error exception

Error indicates that the program encountered a very serious and unrecoverable Error during running. In this case, the application can only stop running, for example, an Error occurs on the JAVA Virtual Machine. An Error is an unchecked Exception. The Compiler does not check whether the Error is handled, and does not need to catch an Error type Exception in the program. Generally, an Error type exception should not be thrown in the program.

3) RuntimeException exception

Exception exceptions include RuntimeException exceptions and other non-RuntimeException exceptions.
RuntimeException is an Unchecked Exception, which indicates that the compiler does not check whether the program processes RuntimeException. in the program, you do not need to capture RuntimException exceptions or throw the RuntimeException class in the method body declaration. When RuntimeException occurs, it indicates that a programming error occurs in the program. Therefore, you should find out the program to modify the error, instead of capturing RuntimeException.

4) Checked Exception

Checked Exception, which is also the most commonly used Exception in programming. All exceptions inherited from Exception and not RuntimeException are checked Exception, IOException and ClassNotFoundException in. The JAVA language requires that the checked Exception must be processed. The Compiler checks the checked Exception, declares that the checked Exception is thrown in the method body, or uses the catch statement to capture the checked Exception for processing. Otherwise, the checked Exception cannot be compiled.

3. Instance

The transaction configuration used here is as follows:

<! -- Jpa transaction configuration --> <bean id = "transactionManager" class = "org. springframework. orm. jpa. jpaTransactionManager "> <property name =" entityManagerFactory "ref =" entityManagerFactory "/> </bean> <! -- Enable annotation transaction --> <tx: annotation-driven transaction-manager = "transactionManager" proxy-target-class = "true"/>

In the spring configuration file, if defaultAutoCommit of the data source is set to TrueCaught exceptions,TransactionsYesWill not roll backIfIf no exception is caught by yourself, the transaction will be rolled back., As shown in the following example:
For example, there is such a record in the configuration file.

<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource"> 

<property name="xxx" value="xxx"/>

<property name="xxx" value="xxx"/>

<property name="defaultAutoCommit" value="true" />


Maybe you will find that you have not configured this parameter, isn't it automatically submitted? The answer is no. Here I use com. alibaba. druid. pool. DruidDataSource as the database connection pool. The default defaultAutoCommit is true. You can refer to the following source code.


Now there are two situations:
Case 1: If no exception is manually caught in the program

@ Transactional (rollbackOn = {Exception. class}) public void test () throws Exception {doDbStuff1 (); doDbStuff2 (); // if the database operation method throws an Exception, the current method doDbStuff1 () database operations will be rolled back. }

Case 2: if an exception is caught in the program

@ Transactional (rollbackOn = {Exception. class}) public void test () {try {doDbStuff1 (); doDbStuff2 (); // if the database operation method throws an exception, the current method doDbStuff1 () database operations are not rolled back. } Catch (Exception e) {e. printStackTrace ();}}

If we need to manually capture exceptions and want to throw exceptions, Can we roll back the swelling?
You can write the following statement to manually roll back the transaction:

@ Transactional (rollbackOn = {Exception. class}) public void test () {try {doDbStuff1 (); doDbStuff2 ();} catch (Exception e) {e. printStackTrace (); TransactionAspectSupport. currentTransactionStatus (). setRollbackOnly (); // This is the sentence. If doDbStuff2 () throws an exception, // doDbStuff1 () rolls back }}

Thank you! Add the original text link for the text transfer. Thank you!

Related Article

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.