Introduction to the use of Spring (7) - Spring Transactions

An overview of database transactions

1. Basic introduction

Transactions must meet the ACID (Atomicity, Consistency, Isolation, and Durability) characteristics, and one of them is indispensable:

  • Atomicity : that is, a transaction is an indivisible smallest unit of work, and operations within a transaction are either all done or not done at all;
  • Consistency : The data in the database is in the correct state before the transaction is executed, and the data in the database is still in the correct state after the transaction is executed, that is, the data integrity constraint is not destroyed; such as bank transfer, A transfers money to B, It must be ensured that A's money must be transferred to B, and there must be no case that A's money is transferred but B does not receive it, otherwise the data in the database will be in an inconsistent (incorrect) state.
  • Isolation : There is no impact between concurrent transaction executions, and operations within one transaction have no impact on other transactions, which requires transaction isolation level to specify isolation;
  • Durability : Once a transaction is successfully executed, its changes to the data in the database must be permanent, and there will be no data inconsistency or loss due to, for example, a system failure or power failure.

In actual project development, database operations are generally executed concurrently, that is, multiple transactions are executed concurrently, and concurrent execution may encounter problems. The current common problems are as follows:

  • Lost update: Two transactions update a row of data at the same time, and the update of the last transaction will overwrite the update of the first transaction, resulting in the loss of the data updated by the first transaction, which is caused by the lack of locking;
  • Dirty read: One transaction sees uncommitted updates from another transaction;
  • Non-repeatable read: In the same transaction, reading the same data multiple times returns different results; that is, other transactions have changed the data;
  • Phantom read: A transaction reads the inserted data committed by another transaction during execution; that is, a batch of data is read at the beginning of the first transaction, but then another transaction inserts new data and commits it. When the first transaction reads this batch of data again but finds one more, it seems like a hallucination.

In order to solve these concurrency problems, it needs to be solved by database isolation levels, and four isolation levels are defined in the standard SQL specification:

  • Uncommitted read (Read Uncommitted ) : the lowest isolation level, a transaction can read the uncommitted update data of other transactions, which is very unsafe, and may have lost updates, dirty reads, non-repeatable reads, and phantom reads;
  • Read Committed : A transaction can read the updated data submitted by other transactions, and cannot see the uncommitted update data. It is impossible to lose updates and dirty reads, but non-repeatable reads and phantom reads may occur;
  • Repeatable Read : It is guaranteed that multiple queries executed successively in the same transaction will return the same result and will not be affected by other transactions. There may be lost updates, dirty reads, and non-repeatable reads, but phantom reads may occur;
  • Serializable (Serializable ) : The highest isolation level, which does not allow concurrent execution of transactions, but must be executed serially. It is the safest and impossible to update, dirty reads, non-repeatable reads, and phantom reads.

2. Transaction type

Database transaction types include local transactions and distributed transactions:

  • Local transaction: It is an ordinary transaction, which can guarantee the ACID of the operation on a single database, and is limited to one database;
  • Distributed transaction: A transaction involving two or more database sources, that is, a transaction spanning multiple homogeneous or heterogeneous databases (composed of local transactions of each database), distributed transactions are designed to ensure that all operations of these local transactions are guaranteed. ACID, so that transactions can span multiple databases;

Java transaction types are JDBC transactions and JTA transactions:

  • JDBC transaction: It is a local transaction in the database transaction type, and the transaction is managed through the control of the Connection object;
  • JTA transaction: JTA refers to the Java Transaction API (Java Transaction API), which is the Java EE database transaction specification. JTA only provides transaction management interfaces, which are implemented by application server vendors (such as WebSphere Application Server). JTA transactions are more powerful than JDBC. Distributed transactions are supported.

 

Second, the transaction manager

1. The core of Spring transaction management is the transaction manager abstraction, which is defined by the PlatformTransactionManager interface:

public  interface PlatformTransactionManager {  
        // According to TransactionDefinition, return an activated transaction or create a new transaction 
       TransactionStatus getTransaction(TransactionDefinition definition) throws TransactionException;  
        // Submit transaction 
       void commit(TransactionStatus status) throws TransactionException;  
        // Rollback transaction 
       void rollback (TransactionStatus status) throws TransactionException;  
}

Two built-in implementations of PlatformTransactionManager:

  • DataSourceTransactionManager : located in the org.springframework.jdbc.datasource package, the data source transaction manager, provides transaction management for a single javax.sql.DataSource, which is used for the transaction management of the Spring JDBC abstract framework and the MyBatis framework;
  • JtaTransactionManager : located in the org.springframework.transaction.jta package, provides support for distributed transaction management, and delegates transaction management to the Java EE application server transaction manager;

 

2. Simple example (programming)

define transaction manager

<bean id="mysql" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close"> 
  ...
</bean>

<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
    <property name="dataSource" ref="mysql"/>
</bean>

test

public class TransactionTest {
    
    private static ApplicationContext context;
    private static PlatformTransactionManager txManager;
    private static DataSource dataSource;
    private static JdbcTemplate jdbcTemplate;
    
    @BeforeClass
    public static void init() {
        context = new ClassPathXmlApplicationContext("spring-context.xml");
        txManager = context.getBean(PlatformTransactionManager.class);
        dataSource = context.getBean(DataSource.class);
        jdbcTemplate = new JdbcTemplate(dataSource);
    }
    
    @Test
    public void testPlatformTransactionManager() {
        DefaultTransactionDefinition def = new DefaultTransactionDefinition();
        def.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED);
        def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);
        TransactionStatus status = txManager.getTransaction(def);
        jdbcTemplate.update("INSERT INTO `user` VALUES(170, 'hello3', 96)");
        //txManager.commit(status);
        txManager.rollback(status);
    }
}

3. Introduction to transaction attributes

Transaction attributes are defined through the TransactionDefinition interface, mainly including transaction isolation level, transaction propagation behavior, transaction timeout time, and whether the transaction is read-only.

i) Isolation level

Used to solve problems with concurrent transactions, specified by static variables in TransactionDefinition:

ISOLATION_DEFAULT: The default isolation level, that is, the default isolation level of the underlying database is used
ISOLATION_READ_UNCOMMITTED: Uncommitted read
ISOLATION_READ_COMMITTED: Commit to read, in general we use this
ISOLATION_REPEATABLE_READ: Repeatable read
ISOLATION_SERIALIZABLE: Serialization

ii) Transaction propagation behavior

Transaction propagation behavior is used to specify how transactions are propagated between multiple transaction methods when they are called. Spring supports a total of 7 propagation behaviors, which are specified by static variables in TransactionDefinition:

PROPAGATION_REQUIRED: If a logical transaction currently exists, join the logical transaction, otherwise a new logical transaction will be created
PROPAGATION_REQUIRES_NEW: create a new logical transaction each time
PROPAGATION_SUPPORTS: If a logical transaction currently exists, join the logical transaction, otherwise execute it in a non-transactional manner
PROPAGATION_NOT_SUPPORTED: If there is currently a logical transaction, suspend the current transaction and execute it in a non-transactional manner
PROPAGATION_MANDATORY: If there is currently a logical transaction, use the current transaction to execute, otherwise throw an exception
PROPAGATION_NEVER: Transactions are not supported, throw an exception if there is currently a transaction
PROPAGATION_NESTED: If a transaction currently exists, it will be executed within a nested transaction. If a transaction does not currently exist, a new transaction will be created. The nested transaction is implemented using savepoints in the database, that is, the rollback of the nested transaction does not affect the outer transaction. , but the outer transaction rollback will cause the nested transaction to rollback

iii) Transaction timeout

Set the timeout time of the transaction, in seconds, the default is -1, which means using the timeout time of the underlying transaction; an exception will be thrown after the transaction times out, and it will cause automatic rollback

new DefaultTransactionDefinition().setTimeout(..); // set a single transaction
DataSourceTransactionManager.setDefaultTimeout(..); // set global

iv) read only

new DefaultTransactionDefinition().setReadOnly(true); 

 

three,

 

 

 

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325214120&siteId=291194637