Home > Java > javaTutorial > Detailed explanation of Java Spring transaction rollback

Detailed explanation of Java Spring transaction rollback

高洛峰
Release: 2017-01-23 10:48:06
Original
1601 people have browsed it

spring transaction rollback

1. Problems encountered

When we have multiple database save operations in one method, an error occurs in the middle database operation. The pseudo code is as follows:

public method() {
  Dao1.save(Person1);
  Dao1.save(Person2);
 
  Dao1.save(Person2);//假如这句发生了错误,前面的两个对象会被保存到数据库中
  Dao1.save(Person2);
}
Copy after login

Expected situation: All database save operations before the error occurs are rolled back, that is, no saving is done

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

When encountering this situation, we can use Spring transactions to solve this problem.

2. Some basic knowledge of exceptions

1) Exception architecture

Exception inheritance structure: Throwable is the base class, Error and Exception inherit Throwable, RuntimeException and IOException, etc. Inherits Exception. Error and RuntimeException and their subclasses become unchecked exceptions (unchecked), and other exceptions become checked exceptions (checked).

Java Spring 事务回滚详解

2) Error exception

Error indicates that a very serious and unrecoverable error occurred during the running of the program. In this case, the application can only Abort the operation, for example, an error occurs in the JAVA virtual machine. Error is an unchecked Exception. The compiler does not check whether the Error has been handled, and there is no need to catch Error type exceptions in the program. Under normal circumstances, exceptions of type Error should not be thrown in programs.

3) RuntimeException exception

Exception exceptions include RuntimeException exceptions and other non-RuntimeException exceptions.
RuntimeException is an Unchecked Exception, which means that the compiler will not check whether the program handles RuntimeException. There is no need to catch exceptions of the RuntimException type in the program, and there is no need to declare the RuntimeException class in the method body. When a RuntimeException occurs, it means that a programming error has occurred in the program, so the error should be found and the program modified instead of catching the RuntimeException.

4) Checked Exception

Checked Exception exception, which is also the most used Exception in programming, all exceptions that inherit from Exception and are not RuntimeException are checked Exception, IOException in the above figure and ClassNotFoundException. The JAVA language stipulates that checked Exception must be processed. The compiler will check this and either declare a checked Exception in the method body or use a catch statement to capture the checked Exception for processing. Otherwise, it cannot be compiled.

3. Example

The transaction configuration used here is as follows:

<!-- Jpa 事务配置 -->
 <bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
   <property name="entityManagerFactory" ref="entityManagerFactory"/>
 </bean>
  
 <!-- 开启注解事务 -->
 <tx:annotation-driven transaction-manager="transactionManager" proxy-target-class="true" />
Copy after login

In the spring configuration file, if the defaultAutoCommit of the data source is set to True , then if the method catches the exception by itself, the transaction will not be rolled back. If the exception is not caught by itself, the transaction will be rolled back, as 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" />
 
</bean>
Copy after login

Maybe you will find that you have not configured this parameter. Will it automatically submit? The answer is no. I use com.alibaba.druid.pool.DruidDataSource as the database connection pool. , the default defaultAutoCommit is true, you can see the source code below

Java Spring 事务回滚详解

Then there are two situations
Case 1: If the exception is not manually caught in the program

@Transactional(rollbackOn = { Exception.class })
public void test() throws Exception {
   doDbStuff1();
   doDbStuff2();//假如这个操作数据库的方法会抛出异常,现在方法doDbStuff1()对数据库的操作  会回滚。
}
Copy after login

Situation 2: If the exception is caught by ourselves in the program

@Transactional(rollbackOn = { Exception.class })
public void test() {
   try {
    doDbStuff1();
    doDbStuff2();//假如这个操作数据库的方法会抛出异常,现在方法doDbStuff1()对数据库的操作 不会回滚。
   } catch (Exception e) {
      e.printStackTrace();  
   }
}
Copy after login

Now what if we need to manually catch the exception and also want to be able to rollback when the exception is thrown? ?
Just write the following to manually roll back the transaction:

@Transactional(rollbackOn = { Exception.class })
public void test() {
   try {
    doDbStuff1();
    doDbStuff2();
   } catch (Exception e) {
     e.printStackTrace();  
     TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();//就是这一句了,加上之后,如果doDbStuff2()抛了异常,                                            //doDbStuff1()是会回滚的
   }
}
Copy after login

Thank you for reading! Thanks!

For more Java Spring transaction rollback related articles, please pay attention to the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template