SoFunction
Updated on 2025-04-17

Spring Boot transaction example detailed explanation

Spring Boot transaction details

introduction

In modern applications, transaction management is an important mechanism to ensure data consistency and integrity. Spring Boot provides powerful transaction management capabilities, allowing developers to easily define and manage transactions. This article will introduce transaction management in Spring Boot in detail, including transaction propagation behavior, transaction properties, and declarative and programmatic transaction management.

Declarative transaction management

Declarative transaction management is to manage transactions through annotations. The most commonly used annotations are@Transactional. This method is simple and intuitive and suitable for most scenarios.

Example

import ;
import ;
@Service
public class UserService {
    @Transactional
    public void createUser(User user) {
        // Database operation    }
}

Programmatic transaction management

Programming transaction management is to manually control transactions through programming, usually usingPlatformTransactionManagerandTransactionTemplate

Example

import ;
import ;
import ;
import ;
import ;
import ;
@Service
public class UserService {
    @Autowired
    private PlatformTransactionManager transactionManager;
    public void createUser(User user) {
        DefaultTransactionDefinition def = new DefaultTransactionDefinition();
        ("createUserTransaction");
        (TransactionDefinition.PROPAGATION_REQUIRED);
        TransactionStatus status = (def);
        try {
            // Database operation            (status);
        } catch (Exception e) {
            (status);
            throw e;
        }
    }
}

Transaction propagation behavior

Transaction propagation behavior defines how transactions propagate when one transaction method calls another transaction method. Spring provides a variety of propagation behaviors that can be used through@TransactionalAnnotations are configured. The following are the propagation behaviors and their usage scenarios supported by Spring:

1. REQUIRED

definition: If a transaction currently exists, join the transaction; if there is no transaction currently, create a new transaction.

Use scenarios: Most business operations use this propagation behavior because it ensures that all operations on the call chain are in the same transaction.

Example

@Transactional(propagation = )
public void methodA() {
    // Business logic}

Transaction propagation diagram

+--------+              +--------+
|  methodA  |              |  methodB  |
|        |--------------->        |
|        | Communication affairs T1    |        |
+--------+              +--------+

2. SUPPORTS

definition: If a transaction currently exists, join the transaction; if there is no transaction currently, it executes in a non-transactional manner.

Use scenarios: Suitable for optional transaction operations, such as read-only queries.

Example

@Transactional(propagation = )
public void methodB() {
    // Business logic}

Transaction propagation diagram

+--------+              +--------+
|  methodA  |              |  methodB  |
|        |--------------->        |
|        | Communication affairs T1    |        |
+--------+              +--------+

3. MANDATORY

definition: If a transaction currently exists, join the transaction; if there is no transaction currently, an exception is thrown.

Use scenarios: Method used to enforce execution in a transactional environment.

Example

@Transactional(propagation = )
public void methodC() {
    // Business logic}

Transaction propagation diagram

+--------+              +--------+
|  methodA  |              |  methodC  |
|        |--------------->        |
|        | Communication affairs T1    |        |
+--------+              +--------+

4. REQUIRES_NEW

definition: Create a new transaction, and if the transaction currently exists, the current transaction will be suspended.

Use scenarios: Applicable to actions that must be performed in a new transaction, such as independent logging.

Example

@Transactional(propagation = Propagation.REQUIRES_NEW)
public void methodD() {
    // Business logic}

Transaction propagation diagram

+--------+              +--------+
|  methodA  |              |  methodD  |
|        |------------->|        |
| Pending transactions T1           | Create a transaction T2 |
+--------+              +--------+

5. NOT_SUPPORTED

definition: Execute operations in a non-transactional manner, and if a transaction currently exists, the current transaction is suspended.

Use scenarios: Suitable for operations that do not require transactions, such as batch data processing.

Example

@Transactional(propagation = Propagation.NOT_SUPPORTED)
public void methodE() {
    // Business logic}

Transaction propagation diagram

+--------+              +--------+
|  methodA  |              |  methodE  |
|        |------------->|        |
| Pending transactions T1           | Non-transaction execution |
+--------+              +--------+

6. NEVER

definition: Execute in a non-transactional manner, and throws an exception if a transaction currently exists.

Use scenarios: A method used to enforce non-transactional execution.

Example

@Transactional(propagation = )
public void methodF() {
    // Business logic}

Transaction propagation diagram

+--------+              +--------+
|  methodA  |              |  methodF  |
|        |------------->|        |
|        | If there is a transaction T1,Throw an exception |
+--------+              +--------+

7. NESTED

definition: If a transaction currently exists, it is executed within a nested transaction; if there is no transaction currently, the behavior isREQUIREDsimilar.

Use scenarios: Applicable to sub-transactions that need to be executed in the main transaction, such as complex database operations.

Example

@Transactional(propagation = )
public void methodG() {
    // Business logic}

Transaction propagation diagram

+--------+              +--------+
|  methodA  |              |  methodG  |
|        |------------->|        |
| Transactions T1             | 嵌套Transactions T1.1 |
+--------+              +--------+

Transaction failure situation

Spring Boot supports transaction operations through the transaction management module of the Spring framework. Transaction management is usually done in Spring Boot@TransactionalAnnotations are implemented. Here are some common transaction failure situations:

1. Uncaught exception

If an uncaught exception occurs in a transaction method and the exception is not processed or propagated outside the transaction boundary, the transaction will fail and all database operations will be rolled back.

2. Unchecked exception

By default, Spring does not detect exceptions (RuntimeExceptionor its subclass) performs rollback processing, which means that when these exceptions are thrown in the transaction method, the transaction will rollback.

3. Improper transaction propagation attribute setting

If there is transaction nesting between multiple transactions and the transaction propagation attribute is incorrectly configured, transaction failure may occur. Especially when calling inside the method@TransactionalPay special attention to the annotation method.

4. Transaction management of multi-data sources

If transaction management is not configured correctly or multiple data sources are present@TransactionalWhen annotating, transactions may be invalidated.

5. Cross-method call transaction issues

If a transaction method calls another method internally, and this called method does not@TransactionalNote: In this case, outer transactions may fail.

6. Transactions fail in non-public methods

if@TransactionalAnnotations are marked on private methods or nonpublicMethodically, the transaction will also fail.

7. Use this to call transaction methods

Spring transactions are controlled through proxy objects, and only through method calls of proxy objects will the relevant rules of transaction management be applied. When usingthisWhen called directly, Spring's proxy mechanism is bypassed, so transaction settings are not applied.

Rollback conditions

1. Automatically roll back transactions

Throw an unchecked exception (RuntimeExceptionand its subclasses), for example:NullPointerExceptionwait.

2. It will not roll back automatically

By default, exceptions are checked (e.g.IOExceptionSQLExceptionetc.) The rollback will not be triggered. Can be passed@TransactionalAnnotatedrollbackForProperties configuration rollback:

Example

@Transactional(rollbackFor = )
public void methodH() {
    // Business logic}

Transaction properties

In addition to propagating behavior, Spring also provides some other transaction properties that can be used through@TransactionalAnnotations are configured.

1. Isolation level

The isolation level defines the extent to which a transaction is isolated from other transactions. Spring supports the following isolation levels:

  • DEFAULT: Use the default isolation level of the database.
  • READ_UNCOMMITTED: Read unsubmitted changes.
  • READ_COMMITTED: Read the submitted changes.
  • REPEATABLE_READ: Repeatable.
  • SERIALIZABLE: Serialization.

Example

@Transactional(isolation = Isolation.READ_COMMITTED)
public void methodI() {
    // Business logic}

2. Transaction timeout

Transaction timeout defines the maximum time (in seconds) a transaction can run before rollback.

Example

@Transactional(timeout = 30)
public void methodJ() {
    // Business logic}

3. Read-only transactions

Read-only transactions are used to optimize read-only operations. Transactions set to read-only can prompt the database engine for some optimizations.

Example

@Transactional(readOnly = true)
public void methodK() {
    // Business logic}

4. Rollback rules

passrollbackForandnoRollbackForThe property can specify which exceptions trigger transaction rollback and which do not.

Example

@Transactional(rollbackFor = )
public void methodL() {
    // Business logic}

Analysis of common interview questions

1. What is transaction communication behavior? What transaction propagation behaviors does Spring provide?

answer: Transaction propagation behavior defines how transactions are propagated when one transaction method calls another transaction method. Spring provides the following transaction propagation behaviors: REQUIRED, SUPPORTS, MANDATORY, REQUIRES_NEW, NOT_SUPPORTED, NEVER, NESTED.

2. How to configure the isolation level of a transaction? What isolation levels does Spring provide?

answer: Can be passed@TransactionalAnnotatedisolationProperties configure the isolation level of the transaction. Spring provides the following isolation levels: DEFAULT, READ_UNCOMMITTED, READ_COMMITTED, REPEATABLE_READ, SERIALIZABLE.

3. What is a read-only transaction? How to configure it?

answer: Read-only transactions are used to optimize read-only operations. Can be passed@TransactionalAnnotatedreadOnlyProperties configure read-only transactions. For example:@Transactional(readOnly = true)

4. How to configure the timeout of a transaction?

answer: Can be passed@TransactionalAnnotatedtimeoutProperties configure the timeout time in seconds for a transaction. For example:@Transactional(timeout = 30)

5. How to specify which exceptions trigger transaction rollback?

answer: Can be passed@TransactionalAnnotatedrollbackForThe property specifies which exceptions trigger transaction rollback. For example:@Transactional(rollbackFor = )

Summarize

Spring Boot provides powerful transaction management capabilities through@TransactionalAnnotations can easily configure the propagation behavior and properties of transactions. Understanding and rationally applying these configurations can effectively improve the data consistency and integrity of the application.

This is the end of this article about the detailed explanation of Spring Boot transaction examples. For more related Spring Boot transaction content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!