Spring transaction (Transaction)

Transactions have four characteristics: atomicity, consistency, isolation and durability, referred to as ACID characteristics.

  • Atomicity: A transaction is an indivisible unit of work, and all actions included in the transaction are either done or none are done.
  • Consistency: Transactions must ensure that the database changes from one consistency state to another. Consistency and atomicity are closely related.
  • Isolation: The execution of a transaction cannot be interfered by other transactions, that is, the operations and data used within a transaction are isolated from other concurrent transactions, and concurrently executed transactions cannot interfere with each other.
  • Durability: Durability, also known as permanence, means that once a transaction is committed, its changes to the data in the database are permanent, and other subsequent operations and failures should not have any impact on it.

Transactions allow us to combine several operations or a group of operations into a unit of work that either all succeeds or all fails. If all operations in the transaction are executed successfully, then everything will be fine. But if any operation in the transaction fails, then all operations in the transaction will be rolled back, and successful operations will be completely cleared, as if nothing happened.

In the real world, probably the most common transaction-related example is a bank transfer. Suppose we need to transfer 1,000 yuan from account A to account B. This transfer operation involves the following two operations.

  • Deduct 100 yuan from account A;
  • Deposit 100 yuan into account B.

If account A successfully deducts 100 yuan, but fails to deposit 100 yuan into account B, then we will lose 100 yuan out of thin air; if account A fails to deduct 100 yuan, but successfully deposits 100 yuan into account B, we will lose 100 yuan out of thin air. If an extra 100 yuan is added to your account out of thin air, the bank will suffer losses. Therefore, we must ensure that all operations in the transaction either succeed or fail. Understanding this, we will grasp the core of the transaction.
 

transaction management style

Spring supports the following two transaction management methods.

transaction management style illustrate
Programmatic transaction management Programmatic transaction management is transaction management implemented by writing code.

This method can accurately define the boundaries of the transaction in the code. We can specify where the transaction starts and where it ends according to the requirements.
Declarative transaction management Spring's declarative transaction management uses AOP technology at the bottom. Its biggest advantage is that there is no need to programmatically manage transactions. You only need to declare relevant rules in the configuration file to apply transaction rules to business logic.

The choice between programmatic transactions and declarative transactions is largely a trade-off between fine-grained control and ease of use.

  • Programmatic control of things is more fine-grained. We can accurately control the boundaries of transactions. The start and end of a transaction completely depend on our needs. However, this method has a fatal shortcoming, that is, the coupling of transaction rules and business code. High degree of complexity and difficult to maintain, so we rarely use this method to manage transactions.
  • Declarative transactions are easier to use, are not intrusive to business code, have low coupling, and are easy to maintain. Therefore, this method is also our most commonly used transaction management method.

Spring's declarative transaction management is mainly implemented in the following two ways:
XML-based declarative transaction management
Annotation-based declarative transaction management

transaction manager

Spring does not manage transactions directly, but manages transactions through a transaction manager.

Spring provides an org.springframework.transaction.PlatformTransactionManager interface. This interface is called Spring's transaction manager. Its source code is as follows

public interface PlatformTransactionManager extends TransactionManager {
    TransactionStatus getTransaction(@Nullable TransactionDefinition definition) throws TransactionException;
    void commit(TransactionStatus status) throws TransactionException;
    void rollback(TransactionStatus status) throws TransactionException;
}

Each method in this interface is described as follows:

name illustrate
TransactionStatus getTransaction(TransactionDefinition definition) Used to obtain transaction status information
void commit(TransactionStatus status) Used to commit transactions
 void rollback(TransactionStatus status) Used to roll back transactions

Spring provides different PlatformTransactionManager interface implementations for different persistence frameworks or platforms (such as JDBC, Hibernate, JPA, JTA, etc.). These implementation classes are called transaction manager implementations.

Implementation class illustrate
org.springframework.jdbc.datasource.DataSourceTransactionManager Used when using Spring JDBC or iBatis to persist data.
org.springframework.orm.hibernate3.HibernateTransactionManager Used when using Hibernate 3.0 and above to persist data.
org.springframework.orm.jpa.JpaTransactionManager Used when using JPA for persistence.
org.springframework.jdo.JdoTransactionManager Used when the persistence mechanism is Jdo.
org.springframework.transaction.jta.JtaTransactionManager Use JTA to implement transaction management, and use this implementation when a transaction spans multiple different resources (i.e., distributed transactions).

TransactionDefinition interface

Spring encapsulates the transaction information in the XML configuration into the object TransactionDefinition, then obtains the status of the transaction (TransactionStatus) through the getTransaction() method of the transaction manager, and performs the next operation on the transaction.

The TransactionDefinition interface provides methods for obtaining transaction-related information. The interface is defined as follows.

public interface TransactionDefinition {
    int getPropagationBehavior();
    int getIsolationLevel();
    String getName();
    int getTimeout();
    boolean isReadOnly();
}

The methods in this interface are described below.

method illustrate
String getName() Get the name of the transaction
int getIsolationLevel() Get the isolation level of a transaction
int getPropagationBehavior() Get transaction propagation behavior
int getTimeout() Get transaction timeout
boolean isReadOnly() Get whether the transaction is read-only

transaction isolation level

A transaction's isolation level defines the extent to which a transaction may be affected by other concurrent transactions.

In practical applications, it is often the case that multiple transactions perform different operations on the same data at the same time to achieve their respective tasks. At this time, problems such as dirty reads, phantom reads, and non-repeatable reads may occur.

In an ideal world, where transactions are completely isolated, the above problems will naturally not arise. However, complete transaction isolation can cause performance problems, and not all applications require complete transaction isolation, so sometimes applications also have certain flexibility in transaction isolation.

Spring provides the following isolation levels. We can choose the appropriate isolation level according to our own needs.

method illustrate
ISOLATION_DEFAULT Use the default isolation level of the backend database
ISOLATION_READ_UNCOMMITTED Allows reading of uncommitted changes, which may result in dirty reads, phantom reads, and non-repeatable reads
ISOLATION_READ_COMMITTED Oracle's default level allows reading of committed concurrent transactions, preventing dirty reads, possible phantom reads and non-repeatable reads.
ISOLATION_REPEATABLE_READ MySQL default level, the results of reading the same field multiple times are consistent, preventing dirty reads and non-repeatable reads, and possible phantom reads.
ISOLATION_SERIALIZABLE Fully comply with ACID isolation level to prevent dirty reads, non-repeatable reads and phantom reads

transaction communication behavior

Transaction propagation behavior refers to how a transaction method should run when it is called by another transaction method. For example, when transaction method A calls transaction method B, whether method B continues to run in the transaction of the caller method A, or starts a new transaction for itself, is determined by the transaction propagation behavior of transaction method B.

Transaction methods refer to methods that can change database table data, such as methods for adding data, deleting data, and modifying data.

Spring provides the following 7 different transaction propagation behaviors.

name illustrate
PROPAGATION_MANDATORY Supports current transactions, and throws an exception if no current transaction exists.
PROPAGATION_NESTED If the current transaction exists, execute within the nested transaction.
PROPAGATION_NEVER The current transaction is not supported and an exception is thrown if the current transaction exists.
PROPAGATION_NOT_SUPPORTED Current transactions are not supported and are always executed in a non-transactional manner.
PROPAGATION_REQUIRED The default propagation behavior is that if the current transaction exists, the current method will be run in the current transaction. If it does not exist, a new transaction will be created and run in the new transaction.
PROPAGATION_REQUIRES_NEW Create a new transaction, or pause the current transaction if one already exists.
PROPAGATION_SUPPORTS The current transaction is supported, and if no transaction exists, it is executed in a non-transactional manner.

TransactionStatus interface

The TransactionStatus interface provides some simple methods to control the execution of transactions and query the status of transactions. The interface is defined as follows.

public interface TransactionStatus extends SavepointManager {
    boolean isNewTransaction();
    boolean hasSavepoint();
    void setRollbackOnly();
    boolean isRollbackOnly();
    boolean isCompleted();
}

Each method in this interface is described below.

name illustrate
boolean hasSavepoint() Get whether a savepoint exists
boolean isCompleted() Get whether the transaction is completed
boolean isNewTransaction() Get whether it is a new transaction
boolean isRollbackOnly() Get whether the transaction is rolled back
void setRollbackOnly() Set transaction rollback
 

Guess you like

Origin blog.csdn.net/qq_43079001/article/details/132232578