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
Top 4 JavaScript Frameworks in 2025: React, Angular, Vue, SvelteTop 4 JavaScript Frameworks in 2025: React, Angular, Vue, SvelteMar 07, 2025 pm 06:09 PM

This article analyzes the top four JavaScript frameworks (React, Angular, Vue, Svelte) in 2025, comparing their performance, scalability, and future prospects. While all remain dominant due to strong communities and ecosystems, their relative popul

How does Java's classloading mechanism work, including different classloaders and their delegation models?How does Java's classloading mechanism work, including different classloaders and their delegation models?Mar 17, 2025 pm 05:35 PM

Java's classloading involves loading, linking, and initializing classes using a hierarchical system with Bootstrap, Extension, and Application classloaders. The parent delegation model ensures core classes are loaded first, affecting custom class loa

How do I implement multi-level caching in Java applications using libraries like Caffeine or Guava Cache?How do I implement multi-level caching in Java applications using libraries like Caffeine or Guava Cache?Mar 17, 2025 pm 05:44 PM

The article discusses implementing multi-level caching in Java using Caffeine and Guava Cache to enhance application performance. It covers setup, integration, and performance benefits, along with configuration and eviction policy management best pra

Spring Boot SnakeYAML 2.0 CVE-2022-1471 Issue FixedSpring Boot SnakeYAML 2.0 CVE-2022-1471 Issue FixedMar 07, 2025 pm 05:52 PM

This article addresses the CVE-2022-1471 vulnerability in SnakeYAML, a critical flaw allowing remote code execution. It details how upgrading Spring Boot applications to SnakeYAML 1.33 or later mitigates this risk, emphasizing that dependency updat

Node.js 20: Key Performance Boosts and New FeaturesNode.js 20: Key Performance Boosts and New FeaturesMar 07, 2025 pm 06:12 PM

Node.js 20 significantly enhances performance via V8 engine improvements, notably faster garbage collection and I/O. New features include better WebAssembly support and refined debugging tools, boosting developer productivity and application speed.

Iceberg: The Future of Data Lake TablesIceberg: The Future of Data Lake TablesMar 07, 2025 pm 06:31 PM

Iceberg, an open table format for large analytical datasets, improves data lake performance and scalability. It addresses limitations of Parquet/ORC through internal metadata management, enabling efficient schema evolution, time travel, concurrent w

How can I implement functional programming techniques in Java?How can I implement functional programming techniques in Java?Mar 11, 2025 pm 05:51 PM

This article explores integrating functional programming into Java using lambda expressions, Streams API, method references, and Optional. It highlights benefits like improved code readability and maintainability through conciseness and immutability

How to Share Data Between Steps in CucumberHow to Share Data Between Steps in CucumberMar 07, 2025 pm 05:55 PM

This article explores methods for sharing data between Cucumber steps, comparing scenario context, global variables, argument passing, and data structures. It emphasizes best practices for maintainability, including concise context use, descriptive

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment