Home Java javaTutorial Detailed explanation of Java Spring transaction rollback

Detailed explanation of Java Spring transaction rollback

Jan 23, 2017 am 10:48 AM

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!

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Is the company's security software causing the application to fail to run? How to troubleshoot and solve it? Is the company's security software causing the application to fail to run? How to troubleshoot and solve it? Apr 19, 2025 pm 04:51 PM

Troubleshooting and solutions to the company's security software that causes some applications to not function properly. Many companies will deploy security software in order to ensure internal network security. ...

How to simplify field mapping issues in system docking using MapStruct? How to simplify field mapping issues in system docking using MapStruct? Apr 19, 2025 pm 06:21 PM

Field mapping processing in system docking often encounters a difficult problem when performing system docking: how to effectively map the interface fields of system A...

How to elegantly obtain entity class variable names to build database query conditions? How to elegantly obtain entity class variable names to build database query conditions? Apr 19, 2025 pm 11:42 PM

When using MyBatis-Plus or other ORM frameworks for database operations, it is often necessary to construct query conditions based on the attribute name of the entity class. If you manually every time...

How do I convert names to numbers to implement sorting and maintain consistency in groups? How do I convert names to numbers to implement sorting and maintain consistency in groups? Apr 19, 2025 pm 11:30 PM

Solutions to convert names to numbers to implement sorting In many application scenarios, users may need to sort in groups, especially in one...

How does IntelliJ IDEA identify the port number of a Spring Boot project without outputting a log? How does IntelliJ IDEA identify the port number of a Spring Boot project without outputting a log? Apr 19, 2025 pm 11:45 PM

Start Spring using IntelliJIDEAUltimate version...

How to safely convert Java objects to arrays? How to safely convert Java objects to arrays? Apr 19, 2025 pm 11:33 PM

Conversion of Java Objects and Arrays: In-depth discussion of the risks and correct methods of cast type conversion Many Java beginners will encounter the conversion of an object into an array...

E-commerce platform SKU and SPU database design: How to take into account both user-defined attributes and attributeless products? E-commerce platform SKU and SPU database design: How to take into account both user-defined attributes and attributeless products? Apr 19, 2025 pm 11:27 PM

Detailed explanation of the design of SKU and SPU tables on e-commerce platforms This article will discuss the database design issues of SKU and SPU in e-commerce platforms, especially how to deal with user-defined sales...

How to elegantly get entity class variable name building query conditions when using TKMyBatis for database query? How to elegantly get entity class variable name building query conditions when using TKMyBatis for database query? Apr 19, 2025 pm 09:51 PM

When using TKMyBatis for database queries, how to gracefully get entity class variable names to build query conditions is a common problem. This article will pin...

See all articles