Detailed explanation of spring transaction management principle and method

Time:2020-12-2

This article mainly introduces the principles and methods of spring transaction management. The article introduces in detail through the example code, which has a certain reference learning value for everyone’s study or work, and friends in need can refer to it

Business, in the daily development or interview will be involved. In the development work, combined with the understanding of database development, it is: a group of DML is either all successfully submitted, or because of an operation exception, the previous successful operation is canceled, and the overall execution fails. Let’s put it simply: live and die together.

From this, we can see the necessity of transaction: in the development work, ensure the security of operation data. Transaction control is to ensure the security of data access.

1、 Four characteristics of transaction

A: Atomicity: all modifications to data are executed successfully or not.

C: Consistency: once the transaction is completed, the system must ensure that the data staff is in a consistent state that meets the business state. It’s a hard explanation. It’s like atomicity. During the operation of a transaction, the data may produce many intermediate states. Consistency ensures that the intermediate states are invisible to other transactions, because these intermediate states are inconsistent with the start and end states of the transaction. That is, from one right state to another.

1: Isolation, the execution of transactions should not affect each other, that is, the independence of transaction execution.

D: Durability: once a transaction is committed, the changes to the database are permanent.

2、 Isolation level of the transaction

In concurrent environment, there may be some problems in transactions, such as dirty read, unreal read, non repeatable read, loss of first type update and second type of update loss.

type explain give an example
Dirty reading Transaction a read the uncommitted data of transaction B A opens the transaction = > b opens the transaction, reads 1000 pieces of account, takes away 100 pieces = > a reads the account amount, reads 900 = > B rolls back the transaction. At this time, the balance data read by a is invalid
Illusory reading An operation in a transaction found data that was not manipulated

A opens the transaction, modifies some data status = > b opens the transaction, executes the new data and commits = > a transaction commit, an unmodified data will appear.

The premise of phantom read is that the addition or deletion action occurs in the concurrent transaction.

Non repeatable In a transaction, the data is read twice, and the results are inconsistent

A opens the transaction, reads the account 1000 yuan = > b opens the transaction, reads the account 1000 yuan, takes out 100 pieces and submits the transaction = > a reads the account balance again, the balance is 900 yuan.

Two identical queries within the scope of a transaction return two different data, which is non repeatable read

The first type of update is missing Transaction a revokes, covering the updated data of transaction B that has been committed A opens the transaction, reads the account 1000 pieces = > b opens the transaction, reads the account 1000 pieces, and then adds 100 pieces, submits the transaction, the account becomes 1100 = > A cancels the rollback transaction, and the account becomes 1000 pieces
The second type of update is missing Transaction a is committed to cover the updated data of transaction B that has been committed A opens the transaction, reads the account 1000 pieces = > b opens the transaction, reads the account 1000 pieces, and then increases 100 pieces, submits the transaction, the account becomes 1100 = > a increases 100 pieces, submits the transaction, the account becomes 1100.

In view of the possible transaction problems in the concurrent environment, the isolation level solutions are proposed, which are read uncommitted, read committed, repeatable read and serializable. The following table shows whether dirty read, phantom read, and non repeatable read will appear at different isolation levels.

type Dirty reading Non repeatable Illusory reading explain
Read uncommitted Meeting Meeting Meeting  
Read committed can’t Meeting Meeting  
Repeatable read can’t can’t Meeting Default isolation level of MySQL
serializable can’t can’t can’t The most strict isolation level, serialization of transactions, low performance.

Query the current isolation level in MySQL: select @ TX_ isolation;

3、 Isolation level and propagation characteristics of spring transaction support

Spring defines five isolation categories and seven communication behaviors org.springframework.transaction . transactiondefinition class)

1. Isolation levels supported by spring

ISOLATION_ Default: the default level. Generally, the isolation level of the database itself (MySQL – repeatable read, Oracle – read committed) is used

Remaining isolation_ READ_ UNCOMMITTED、ISOLATION_ READ_ COMMITTED、ISOLATION_ REPEATABLE_ READ、ISOLATION_ Serializable corresponds to the above database isolation level configuration respectively.

2. Propagation characteristics

The propagation feature of transaction is how to use propagation between methods when multiple transaction methods call each other

  • PROPAGATION_ Required: if there is a current transaction, it is added to the transaction. If not, create a new transaction.
  • PROPAGATION_ Supports: if there is a current transaction, it is added to the transaction. If not, it runs in a non transactional state.
  • PROPAGATION_ Mandatory: if there is a current transaction, it will be added to the transaction. If not, a no transaction exception is thrown
  • PROPAGATION_ REQUIRES_ New: creates a new transaction. If a transaction currently exists, the transaction is suspended.
  • PROPAGATION_ NOT_ Non transaction state: supported. If a transaction currently exists, the transaction is suspended.
  • PROPAGATION_ Never: runs in a non transactional state. If a transaction currently exists, an exception is thrown.
  • PROPAGATION_ Nested: nested transactions (parent-child transactions) are executed if there are currently transactions. If not, it is similar to propagation_ Required processing.

The default propagation behavior of spring is propagation_ Required, generally applicable to the vast majority of development work.

3. Timeout property of the transaction

If the transaction has not completed the operation within a predetermined time, the transaction will be rolled back automatically. In the transactiondefinition, int is used to represent the timeout time, and the unit is seconds. The default value provided is timeout_ Default = – 1, that is, never time out and wait for the operation to complete

4、 Spring transaction configuration method

Spring does not manage transactions directly, but provides an interface org.springframework.transaction . platformtransactionmanager, the interface mainly defines three methods: gettransaction (get transaction), commit (COMMIT) and rollback (rollback).

According to different persistence strategies, spring provides different implementations, such as JDBC-

org.springframework.jdbc . datasource.DataSourceTransactionManager 、hibernate – org.springframework.orm . hibernate5. Hibernatetransaction manager, etc. in other implementations, you can query through the source code.

Spring transaction can be divided into programming transaction and declarative transaction. Every time a programming transaction is used, it is necessary to write and obtain the transaction, set the transaction isolation level and propagation characteristics, and commit or roll back the transaction. The code repetition is too high, which is time-consuming and laborious. If the functionality of the code is complex, it becomes more painful to use programming. The declarative transaction is non-invasive, does not affect the main business process, and is very simple to write. Therefore, in current development work, declarative transactions are more often used.

1. Programming transaction

//to do。 Follow up supplement

2. Declarative transaction

There are two kinds of declarative transactions: AOP based weaving and @ transactional annotation.

2.1. Transaction weaving based on AOP

After defining methods in servcie, the best way is to start with the format defined in TX: method, and specific transactions will be executed.

2.2 annotation transaction

The configuration of data source and transaction manager in the first part of annotation transaction is the same as above. What needs to be modified in the configuration file is to enable annotation configuration

Then, in service programming, you can annotate @ transactional (it is recommended to only add it in the service implementation class). The following is a sample configuration, in which the properties can be set as needed:


@Transactional(propagation = Propagation.REQUIRED,isolation = Isolation.REPEATABLE_READ,timeout = 100, readOnly = false, rollbackFor = {},noRollbackFor = {})

Note:

The exception rollback of a transaction only checks the exception of runtimeException. The checked exception (such as classnotfoundexception, FileNotFoundException, etc.) will not roll back. If the exception is caught, it will not be thrown or rolled back.

5、 Spring and spring MVC parent child containers

Now in the development work, most of them use spring and spring MVC. Here, spring container and spring MVC container constitute the parent-child relationship. The parent container spring cannot find the beans in the child container spring MVC, while the child container can find the beans registered in the parent container. Therefore, in the actual development work, if we don’t pay attention to it, we often have some unexpected problems.

First, we usually configure the spring configuration file applicationContext.xml The following scanning will be configured:

<context:component-scan base-package="com.cfang" />

This configuration will scan all @ component type annotations under the specified package, including @ controller, @ service, @ repository, and register the scanned beans into the spring container.

Generally, the following configuration will appear in the spring configuration file to scan @ required, @ Autowired, @ postconstruct, @ persistencecontext, @ resource, @ predestroy and other annotations. In theory, this configuration is optional because the scan configuration above is turned on by default.


<context:annotation-config/>

Next, configure the configuration file spring of spring MVC- mvc.xml , configure scanning annotations @ requestmapping, @ requestbody, @ ResponseBody, etc. at the same time, many parameter binding methods are loaded by default.


<mvc:annotation-driven />

The above sentence is equivalent to:

<! -- configure annotation controller mapper, which is used in spring MVC to map request URL to specific controller -- >
<bean/>
<! -- configure annotation controller mapper, which is used in spring MVC to map specific requests to specific methods -- >
<bean/>

After talking about the basic configuration above, let’s take a look at the possible container conflicts and their impact on transaction management.

First, there are two basic containers: spring and spring MVC, with configuration files of applicationContext.xml And spring- mvc.xml

1、 applicationContext.xml Medium configuration< context:component-scan base-package= ” com.cfang “/ >, scan all beans under the specified package, and automatically register them in the spring container

2、spring- mvc.xml Configuration< mvc:annotation-driven / >, scan the relevant spring MVC annotations

3. In order to ensure the normal jump of spring MVC, we usually have to use spring- mvc.xml Configure package scanning in file< context:component-scan base-package= ” com.cfang ” />。

According to the above configuration information, transaction failure will occur. The reason is that:

Spring container is loaded first by servletcontextlistener (corresponding to applicationContext.xml )The generated parent container,

And spring MVC (corresponding to spring- mvc.xml )What is produced is a child container. The instance of @ service annotation configured in the sub container controller during scanning and assembling is a service without transaction enhancement, that is, without transaction processing capability,

The service initialized by the parent container ensures the enhanced processing ability of the transaction. If the service is not excluded from the sub container, the service with no transaction processing capacity will be obtained.

The solution is configured according to the official recommendation, and each is responsible for part of the loading:

Spring scan:


<context:component-scan base-package="com.cfang.WeChat" use-default-filters="false">
    <context:include-filter type="annotation" expression="org.springframework.stereotype.Repository"/>
    <context:include-filter type="annotation" expression="org.springframework.stereotype.Service"/>
  </context:component-scan>

Spring MVC scan:


<context:component-scan base-package="com.cfang.WeChat" use-default-filters="false">
    <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
  </context:component-scan>

The above is the whole content of this article, I hope to help you in your study, and I hope you can support developeppaer more.