SoFunction
Updated on 2025-03-08

How to implement management transactions in Spring

Spring controls the boundaries and behavior of transactions through programmatic transactions and declarative transaction management.

1. Transaction Manager

Spring manages transactions through a Transaction Manager. Different persistence technologies (such as JDBC, JPA, Hibernate) correspond to different transaction managers, for example:

  • DataSourceTransactionManager: Used to manage JDBC transactions.
  • JpaTransactionManager: Used to manage JPA transactions.
  • HibernateTransactionManager: Used to manage Hibernate transactions.

The transaction manager is the core of Spring transaction management, which handles the start, commit and rollback of transactions.

2. Programming transaction management

Programmatic transaction management refers to explicitly managing transactions in code, usually usingTransactionTemplateOr the underlyingPlatformTransactionManager

Using TransactionTemplate

@Autowired
private TransactionTemplate transactionTemplate;

public void someMethod() {
    (status -> {
        // Execute business logic        // (); // Roll back the transaction        return null;
    });
}

Using PlatformTransactionManager

@Autowired
private PlatformTransactionManager transactionManager;

public void someMethod() {
    DefaultTransactionDefinition def = new DefaultTransactionDefinition();
    TransactionStatus status = (def);

    try {
        // Execute business logic        (status); // Submit transaction    } catch (Exception e) {
        (status); // Roll back the transaction    }
}

3. Declarative transaction management

Declarative transaction management is used to manage transactions through AOP (sectional-oriented programming) and annotations, usually using@Transactionalannotation.

This method is more concise and convenient, and is recommended.

Use @Transactional annotation

import ;

@Service
public class MyService {

    @Transactional
    public void someMethod() {
        // Execute business logic    }
}

@TransactionalAnnotations can be applied to classes or methods, and its main properties include:

  • propagation: The propagation behavior of a transaction, defining how a transaction is propagated. Commonly used propagation behaviors include:

    • REQUIRED(Default): If a transaction is currently present, join the transaction; if there is currently no transaction, create a new transaction.
    • REQUIRES_NEW: Always create a new transaction, and if the transaction currently exists, the current transaction is suspended.
    • SUPPORTS: If a transaction currently exists, join the transaction; if there is no transaction currently, it executes in a non-transactional manner.
    • NOT_SUPPORTED: Always execute in a non-transactional manner, and if a transaction currently exists, the current transaction is suspended.
    • MANDATORY: Must be executed in a transaction, and an exception is thrown if there is currently no transaction.
    • NEVER: Must be executed in a non-transaction, and an exception is thrown if a transaction is currently present.
    • NESTED: Create a nested transaction if there is currently a transaction; if there is currently no transaction, create a new transaction.
  • isolation: The isolation level of a transaction, defining the extent to which a transaction can be affected by other transactions. Commonly used isolation levels include:

    • DEFAULT(Default): Use the default isolation level of the underlying database.
    • READ_UNCOMMITTED: The lowest isolation level, allowing dirty reading.
    • READ_COMMITTED: No repetitive reading is allowed to prevent dirty reading.
    • REPEATABLE_READ: Allow phantom reading to prevent dirty reading and non-repeatable reading.
    • SERIALIZABLE: The highest isolation level to prevent dirty reading, non-repeatable reading and phantom reading.
  • timeout: Transaction timeout, in seconds. The default value is -1, indicating that there is no timeout limit.

  • readOnly: Whether it is a read-only transaction. The default value isfalse. Read-only transactions are often used for query operations and can be optimized for certain databases.

  • rollbackFor: Specify which exceptions will cause transaction rollback. For example:rollbackFor =

  • noRollbackFor: Specify which exceptions will not cause transaction rollback. For example:noRollbackFor =

4. Transaction propagation and isolation levels

Transaction propagation and isolation levels are important concepts in Spring transaction management.

  • Transaction Propagation: Defines the propagation behavior of the transaction when the transaction method is called. For example, whether the current method is to run in a transaction, whether it is to join an existing transaction, or whether it is to start a new transaction.
  • Isolation level: Defines the extent to which one transaction can see the impact of other transactions on the data. Common isolation levels include:READ_UNCOMMITTEDREAD_COMMITTEDREPEATABLE_READSERIALIZABLE

Example: Configuring and Using Transactions

Configuring Spring Transaction Management

In Spring Boot, you only need to add it to the main class or configuration class@EnableTransactionManagementannotation:

import ;
import ;

@Configuration
@EnableTransactionManagement
public class AppConfig {
    // Configure data sources and transaction managers, etc.}

Use @Transactional annotation

import ;
import ;

@Service
public class UserService {

    @Transactional
    public void createUser(User user) {
        // Create user's business logic    }
}

Summarize

Spring's transaction management mechanism provides flexible transaction control through two methods: programmatic transaction management and declarative transaction management.

Declarative transaction management is the most commonly used method, through@TransactionalAnnotation allows easy control of transaction propagation behavior, isolation level, timeout time and rollback rules.

The power and flexibility of Spring transaction management mechanism enable developers to easily handle complex transaction scenarios and ensure data consistency and integrity.

The above is personal experience. I hope you can give you a reference and I hope you can support me more.