Basic Introduction
Programmatic Transaction
Adding transaction control code in business logic. This transaction control mechanism is called programmatic transaction.
Declarative Transaction
Achieving transaction control through XML or annotation configuration is called declarative transaction.
Transaction Control
Transaction Concept
A transaction is a logically grouped operation where all units either succeed completely or fail completely. This ensures data accuracy and security.
Four Characteristics
Atomicity
Atomicity means a transaction is an indivisible work unit. All operations in a transaction either all occur or none occur.
Consistency
A transaction must transform the database from one consistent state to another. For example, before transfer A has 1000 and B has 1000; after transfer A+B=2000.
Isolation
Isolation means that when multiple users concurrently access the database, the database opens a transaction for each user. Each transaction cannot be interfered with by data operations from other transactions. Multiple concurrent transactions must be isolated from each other.
Durability
Durability means once a transaction is committed, changes to the database data are permanent. Subsequent database failures should have no effect on it.
Isolation Levels
Serializable
Can avoid dirty read, non-repeatable read, and phantom read.
Repeatable Read
Can avoid dirty read and non-repeatable read (but phantom read may occur). UPDATE operations require locking in this case.
Read Committed
Can avoid dirty read, but non-repeatable read and phantom read will definitely occur.
Read Uncommitted
Lowest level, none of the above situations can be guaranteed.
Default Level
MySQL’s default isolation level is: Repeatable Read
Query current isolation level:
SELECT @@tx_isolation;
Set MySQL transaction isolation level, only valid for current session, invalid when closed:
set session transaction isolation level xxx;
Spring Transaction API
Spring’s internal classes are as follows:
package org.springframework.transaction;
import org.springframework.lang.Nullable;
public interface PlatformTransactionManager {
TransactionStatus getTransaction(@Nullable TransactionDefinition definition)
throws TransactionException;
void commit(TransactionStatus status) throws TransactionException;
void rollback(TransactionStatus status) throws TransactionException;
}
Function: This interface is Spring’s transaction manager core interface. Spring itself does not support transaction implementation, only provides standards. What kind of transactions the underlying application supports requires specific implementation classes. This is also the specific application of the Strategy pattern.
In the Spring framework, it also provides some built-in concrete strategies, such as: DataSourceTransactionManager, etc. DataSourceTransactionManager is ultimately cross-cutting logic code. Declarative transaction is to use AOP (dynamic proxy) to weave transaction control logic into business code.