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"
   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xmlns:tx="http://www.springframework.org/schema/tx"
   xmlns:aop="http://www.springframework.org/schema/aop"
   xsi:schemaLocation="http://www.springframework.org/schema/beans
   http://www.springframework.org/schema/beans/spring-beans-3.0.xsd 
   http://www.springframework.org/schema/tx
   http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
   http://www.springframework.org/schema/aop
   http://www.springframework.org/schema/aop/spring-aop-3.0.xsd">

   <!-- Initialization for data source -->
   <bean id="dataSource" 
      class="org.springframework.jdbc.datasource.DriverManagerDataSource">
      <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"/>
   </bean>

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

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

   <!-- Initialization for TransactionManager -->
   <bean id="transactionManager"
   class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
      <property name="dataSource"  ref="dataSource" />    
   </bean>

   <!-- Definition for studentJDBCTemplate bean -->
   <bean id="studentJDBCTemplate"  
   class="com.tutorialspoint.StudentJDBCTemplate">
      <property name="dataSource"  ref="dataSource" />  
   </bean>

</beans>

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
 @Transactional(rollbackFor=Exception.class)
    public void insert(String sql, boolean flag) throws Exception {
        dao.insertSql(sql);
        // 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