[SSM-Spring Chapter 06]-Transaction-Spring Transaction Management

1. Affairs

1.1 Characteristics of transactions

Transaction has four characteristics of ACID:

  Atomicity : A transaction is an indivisible unit of work. The operations in the transaction either all happen or do not have
  consistency (Consistency) : After the transaction is completed, the integrity of the data must maintain consistent
  isolation (Isolation) : When multiple users access the database concurrently, the transaction of one user cannot be interfered by the transactions of other users, and the data between multiple concurrent transactions must be isolated from each other
  . Durability : Once a transaction is submitted, it will affect the data in the database. The change should be permanent, even if the database fails, it should not have any impact on it

  If an exception/error occurs in any place during the entire transaction execution process, the transaction will be rolled back, and the data state after the rollback will be exactly the same as before the transaction execution.


1.2 Transaction isolation level

  The isolation level refers to the degree of isolation between several concurrent transactions. There are five constants that represent isolation levels defined in the TransactionDefinition interface:

TransactionDefinition interface transaction isolation level description
ISOLATION_DEFAULT The default value indicates that the default isolation level of the underlying database is used. For most databases, this value is usually TransactionDefinition.ISOLATION_READ_COMMITTED
ISOLATION_READ_UNCOMMITTED The isolation level means that a transaction can read data modified by another transaction but not yet committed. This level cannot prevent dirty reads, non-repeatable reads and phantom reads , so this isolation level is rarely used.
ISOLATION_READ_COMMITTED This isolation level means that a transaction can only read data that has been committed by another transaction. Can prevent dirty reads , which is the recommended value in most cases.
ISOLATION_REPEATABLE_READ This isolation level means that a transaction can execute a query multiple times during the entire process, and the records returned each time are the same. This level can prevent dirty reads and non-repeatable reads .
ISOLATION_SERIALIZABLE All transactions are executed one by one, and there is absolutely no possibility of interference between transactions. This level can prevent dirty reads, non-repeatable reads, and phantom reads . But this will seriously affect the performance of the program . Normally, this level is not used either.

1.3 The propagation characteristics of transactions

  Transaction propagation characteristics: If a transaction context already exists before starting the current transaction, there are several options to specify the execution behavior of a transactional method.
  These constants representing the propagation behavior defined in TransactionDefinition

TransactionDefinition transaction propagation behavior constant description
PROPAGATION_REQUIRED Defaults. If there is currently a transaction, join the transaction; if there is no current transaction, create a new transaction
PROPAGATION_REQUIRES_NEW Create a new transaction, if there is a current transaction, then suspend the current transaction
PROPAGATION_SUPPORTS If there is currently a transaction, then join the transaction; if there is no current transaction, continue to run in a non-transactional manner
PROPAGATION_NOT_SUPPORTED Run in non-transactional mode. If there is a transaction currently, the current transaction is suspended.
PROPAGATION_NEVER Run in non-transactional mode. If there is a transaction currently, an exception is thrown.
PROPAGATION_MANDATORY If there is a transaction currently, it will join the transaction; if there is no transaction currently, an exception will be thrown.
PROPAGATION_NESTED If there is a transaction currently, a transaction is created to run as a nested transaction of the current transaction; if there is no transaction currently, the value is equivalent to TransactionDefinition.PROPAGATION_REQUIRED.

1.4 Transaction rollback rules

  In the default configuration, Spring rolls back the transaction only when the thrown exception is a runtime unchecked exception, that is, the thrown exception is a subclass of RuntimeException (Errors will also cause the transaction to roll back), and a checked exception is thrown. Will not cause the transaction to roll back . You can explicitly configure which exceptions are thrown to roll back the transaction, including checked exceptions. You can also clearly define those transactions that are not rolled back when exceptions are thrown. You can also programmatically use the setRollbackOnly() method to indicate that a transaction must be rolled back. The only operation you can perform after calling setRollbackOnly() is to roll back.

2. Spring transaction management

  Spring transaction management is divided into programmatic transaction management and declarative transaction management

2.1 Declarative transaction management

  Declarative transactions are built on AOP. Its essence is to intercept before and after the method , then create or add a transaction before the target method starts, and submit or roll back the transaction according to the execution after the target method is executed.
  The biggest advantage of declarative transaction management is that there is no need to manage transactions through programming, so there is no need to add transaction processing code to the business logic code. You only need to declare the relevant transaction rules to apply the transaction rules to the business logic.

//如果不想某个异常进行事务处理
@Transactional(rollbackFor=RuntimeException.class)//不对RuntimeException回滚生效
@Transactional(rollbackFor=Exception.class)// 不对Exception回滚生效

  Spring's declarative transaction management can be achieved in two ways:

  1. Based on @Transactional annotation .
  2. XML-based approach

2.1.1 Based on @Transactional annotation

  Add the @Transactional annotation directly to the method of the Service layer.
Configure the transaction manager in applicationContext.xml

	<!--  事务管理器 完成手动事务管理-->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"/>
    </bean>

    <!--打开注解事务管理-->
    <tx:annotation-driven transaction-manager="transactionManager"/>

Case realization: https://github.com/strive-xgf/SSM/commit/d855985d82db5d969a9e9820fe0686f8ce9341bc



2.1.2 XML-based approach

  • The XML-based declarative transaction management is realized by configuring relevant declarations of transaction rules in the configuration file. The Spring framework provides tx namespace to configure transactions .
  • tx:advice element to configure the notification of the transaction . When configuring the tx:advice element, you generally need to specify the id and transaction-manager attributes, where the id attribute is a unique identifier in the configuration file, and the transaction-manager attribute specifies the transaction manager.
  • The tx:attributes sub-element can be configured with multiple tx:method sub-elements to specify the details of the transaction.
  • After the tx:advice element is configured with enhanced transaction processing, you can write AOP configuration to let Spring automatically generate a proxy for the target object.

  Need to configure transactions and notifications in applicationContext.xml

Case realization: https://github.com/strive-xgf/SSM/commit/61cae51d9a69975ab2caa75249c84d484accff83

2.2 Programmatic transaction management

  Programmatic transaction management based on the underlying API is to perform transaction processing programmatically according to the three core interfaces of PlatformTransactionManager, TransactionDefinition and TransactionStatus. Spring recommends using TransactionTemplate . Explicitly call beginTransaction() , commit() , **rollback() ** and other transaction-related methods
  in the code , which is programmatic transaction management.

  The execute() method of TransactionTemplate has a parameter of TransactionCallback interface type. The interface defines a doInTransaction() method, which usually implements the TransactionCallback interface in the form of an anonymous inner class, and writes business logic code in its doInTransaction() method. The default transaction commit and rollback rules can be used here, and there is no need to explicitly call any transaction API in the business code. The doInTransaction() method has a TransactionStatus type parameter. The setRollbackOnly() method of this parameter can be called anywhere in the method to mark the transaction as a rollback to perform the transaction rollback.
  According to the default rules, if an unchecked exception is thrown during the execution of the callback method, or the setRollbackOnly() method is explicitly called, the transaction is rolled back; if the transaction is completed or a checked exception is thrown, the transaction is committed .

Case realization: https://github.com/strive-xgf/SSM/commit/fe39a52b5d2f6c692db7ed0a373c6e327cb8a267

Guess you like

Origin blog.csdn.net/qq_40542534/article/details/108695147