Spring transaction management

1, Transaction Basics

1. Transaction definition

2. Four characteristics of transaction

  1. Atomicity
    Transaction is the logical work unit of database. All operations included in transaction are either done or not done at all.
  2. Consistency
    The result of transaction execution must be to change the database from one consistency state to another. Consistency and atomicity are closely related.
  3. Isolation
    The execution of one transaction cannot be disturbed by other transactions.
  4. Sustainability
    Once a transaction is committed, its changes to the data in the database should be permanent.

3. Problems caused by concurrent transactions

  • Dirty reads - dirty reads occur when a transaction reads data overwritten by another transaction but not yet committed. If the rewrite is rolled back later, the data obtained by the first transaction is invalid.
  • Nonrepeatable read - nonrepeatable read occurs when a transaction executes the same query twice or more, but gets different data each time. This is usually because another concurrent transaction is updated during two queries.
  • Phantom read - Phantom reading is similar to non repeatable reading. It occurs when a transaction (T1) reads several rows of data and then another concurrent transaction (T2) inserts some data. In the subsequent query, the first transaction (T1) will find more records that do not exist.

4. Isolation level of transaction

Isolation levelSolve the problem of concurrent transactions
Read uncommittedAt the lowest level, there is no guarantee under any circumstances
Read committedDirty reading
Repeatable readDirty reading, non repeatable reading
SerializableDirty reading, unrepeatable reading, unreal reading

2, Transaction management in Spring

1. Transaction management interface in Spring

Interface relationships involved in Spring transaction management:

Spring does not directly manage transactions, but provides a variety of transaction managers. They delegate the responsibility of transaction management to the transactions of relevant platform frameworks provided by persistence mechanisms such as Hibernate or JTA.

  • The key to Spring transaction abstraction is that
    org. springframework. transaction. The platformtransactionmanager interface is defined as follows:
public interface PlatformTransactionManager {
   TransactionStatus getTransaction(TransactionDefinition definition) throws TransactionException;
   void commit(TransactionStatus status) throws TransactionException;
   void rollback(TransactionStatus status) throws TransactionException;

  • TransactionDefinition is the core interface supported by transactions in Spring. Its definition is as follows:
public interface TransactionDefinition {
   int getPropagationBehavior();
   int getIsolationLevel();
   String getName();
   int getTimeout();
   boolean isReadOnly();

The following are possible values for the isolation level:

The following are the possible values of the propagation type:

  • The TransactionStatus interface provides a simple method for transaction code to control transaction execution and query transaction status.
public interface TransactionStatus extends SavepointManager {
   boolean isNewTransaction();
   boolean hasSavepoint();
   void setRollbackOnly();
   boolean isRollbackOnly();
   boolean isCompleted();

2. Transaction usage in Spring

2.1. xml configuration file based on tx and aop namespace

Example of transaction configuration using XML in Spring:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"

   <!-- Initialization for data source -->
   <bean id="dataSource" 
      <property name="driverClassName" value="com.mysql.jdbc.Driver"/>
      <property name="url" value="jdbc:mysql://localhost:3306/TEST"/>
      <property name="username" value="root"/>
      <property name="password" value="cohondob"/>

   <tx:advice id="txAdvice"  transaction-manager="transactionManager">
      <tx:method name="create"/>

      <aop:pointcut id="createOperation" 
      expression="execution(* com.tutorialspoint.StudentJDBCTemplate.create(..))"/>
      <aop:advisor advice-ref="txAdvice" pointcut-ref="createOperation"/>

   <!-- Initialization for TransactionManager -->
   <bean id="transactionManager"
      <property name="dataSource"  ref="dataSource" />    

   <!-- Definition for studentJDBCTemplate bean -->
   <bean id="studentJDBCTemplate"  
      <property name="dataSource"  ref="dataSource" />  


2.2 annotation based on @ Transactional

  1. Open annotation in configuration file
  <!-- Annotation injection of declarative transaction management configuration things-->
    <tx:annotation-driven transaction-manager="transactionManager"/>
  1. Add @ Transactional annotation to the method requiring transaction management
    public void insert(String sql, boolean flag) throws Exception {
        // If flag is true, an exception is thrown
        if (flag){
            throw new Exception("has exception!!!");

In addition, transactions are also divided into programmatic transactions and declarative transactions. Because of the high coupling degree of programmatic transactions, declarative transaction development is more used in actual development.

3. Implementation of Spring transaction management interface

4. @ Transactional transaction implementation mechanism

When the application system calls and declares the target method of @ Transactional, the Spring Framework uses AOP proxy by default, and generates a proxy object during code running. According to the attribute configuration information of @ Transactional, this proxy object determines whether the target method of @ Transactional is intercepted by the interceptor TransactionInterceptor, When intercepted by the TransactionInterceptor, the transaction will be created and added before the target method starts to execute, and the logic of the target method will be executed. Finally, according to whether there is an exception in the execution, the AbstractPlatformTransactionManager will be used to manage the operation of the data source, and the DataSource will commit or roll back the transaction.
Spring AOP proxy has two types: CglibAopProxy and JdkDynamicAopProxy. Take CglibAopProxy as an example. For CglibAopProxy, you need to call the intercept method of the dynamicadisaidedinterceptor of its internal class. For JdkDynamicAopProxy, you need to call its invoke method.

Keywords: Java Spring Back-end

Added by j9sjam3 on Sun, 06 Mar 2022 12:31:18 +0200