search
HomeJavajavaTutorialDetailed explanation of Java Spring transaction rollback

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);
}

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" />

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>

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()对数据库的操作  会回滚。
}

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();  
   }
}

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()是会回滚的
   }
}

Thank you for reading! Thanks!

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

Statement
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
How to add complex borders to Excel cells using GrapeCity Documents for Java library in Java?How to add complex borders to Excel cells using GrapeCity Documents for Java library in Java?Apr 19, 2025 pm 08:39 PM

Using POI library in Java to add borders to Excel files Many Java developers are using Apache...

How to use CompletableFuture to ensure the order consistency of batch interface request results?How to use CompletableFuture to ensure the order consistency of batch interface request results?Apr 19, 2025 pm 08:36 PM

Efficient processing of batch interface requests: Using CompletableFuture to ensure that concurrent calls to third-party interfaces can significantly improve efficiency when processing large amounts of data. �...

In JavaWeb applications, is it reasonable for Dao layer to cache all personnel entity classes?In JavaWeb applications, is it reasonable for Dao layer to cache all personnel entity classes?Apr 19, 2025 pm 08:33 PM

In JavaWeb applications, the feasibility of implementing entity-class caching in Dao layer When developing JavaWeb applications, performance optimization has always been the focus of developers. Either...

Which motorcycle and motorcycle system is better? Comparison of advantages and disadvantages between open Android system and closed self-developed systemWhich motorcycle and motorcycle system is better? Comparison of advantages and disadvantages between open Android system and closed self-developed systemApr 19, 2025 pm 08:30 PM

The current status of motorcycle and motorcycle systems and ecological development of motorcycle systems, as an important bridge connecting knights and vehicles, has developed rapidly in recent years. Many car friends...

How to get Java entity class attribute names elegantly to avoid hard-coded in MyBatis queries?How to get Java entity class attribute names elegantly to avoid hard-coded in MyBatis queries?Apr 19, 2025 pm 08:27 PM

When using MyBatis-Plus or tk.mybatis...

How to efficiently query personnel data in MySql and ElasticSearch through natural language processing?How to efficiently query personnel data in MySql and ElasticSearch through natural language processing?Apr 19, 2025 pm 08:24 PM

How to query personnel data through natural language processing? In modern data processing, how to efficiently query personnel data is a common and important requirement. ...

How to parse next-auth generated JWT token in Java and get information in it?How to parse next-auth generated JWT token in Java and get information in it?Apr 19, 2025 pm 08:21 PM

In processing next-auth generated JWT...

See all articles

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

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)