Spring (five) spring transaction processing

Spring (five) spring transaction processing

Source download

Article Directory

1. Spring's transaction management

1.1 What is a transaction

​ Transaction refers to a set of sql statements. There are multiple sql statements in the set. They
may be insert, update, select, delete. We hope that these multiple sql statements can succeed,
or all fail, the execution of these sql statements Is consistent and executed as a whole

1.2 When to use transactions


Note: the Java code should be placed on the transaction service business methods class, because business methods will call multiple methods dao, execute multiple sql statements

1.3 How do JDBC and mybatis handle transactions?

​ jdbc access to the database, process transactions Connection conn; conn.commit(); conn.rollback();
​ mybatis access to the database, process transactions, SqlSession.commit(); SqlSession.rollback();
​ hibernate access to the database, process transactions, Session.commit(); Session.rollback();

1.4 Disadvantages of transaction processing in different databases

  1. Different database access technologies, transaction objects and methods are different, you
    need to understand the principles of different database access technologies using transactions
  2. Master the processing logic of transactions in a variety of databases. When to commit the transaction and when to review the transaction
  3. Multiple ways to handle affairs.

Summary : It is a variety of database access technologies, with different transaction processing mechanisms, objects, and methods.

1.5 How to solve the shortcomings of different technologies

Spring provides a unified model for handling transactions, which can be completed in a unified way

​ Transaction processing of a variety of different database access technologies.

Using spring transaction processing mechanism, you can complete the transaction processing of mybatis accessing the database.
Using spring transaction processing mechanism, you can complete the transaction processing of hibernate accessing the database.

Second, how does spring handle transactions?

2.1 Transaction Manager

Interface: PlatformTransactionManager, which defines the important transaction methods commit and rollback

Implementation class: Spring has created the transaction processing class corresponding to each database access technology.

​ Two interface implementation classes are mainly used:

  1. mybatis access database-spring created DataSourceTransactionManager
  2. Hibernate access to the database-spring created HibernateTransactionManager

Usage: You need to tell spring which database access technology you use

​ Declare the transaction manager implementation class of the database access technology, use the declaration in the spring configuration file

For example: you want to use mybatis to access the database, you should be in the xml configuration file

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

2.2 Explain the type of transaction

The transaction attributes that need to be explained are:

Isolation level of the transaction : There are 4 values.

  1. DEFAULT: Use the DB default transaction isolation level. MySql defaults to REPEATABLE_READ; Oracle defaults to READ_COMMITTED.
  2. READ_UNCOMMITTED: Read has not been submitted. No concurrency issues have been resolved.
  3. READ_COMMITTED: Read has been submitted. Solve dirty reads, there are non-repeatable reads and phantom reads.
  4. REPEATABLE_READ: Repeatable reading. Solve dirty reads, non-repeatable reads, and phantom reads
  5. SERIALIZABLE: Serialization. There is no concurrency problem.

Transaction timeout time : indicates the longest execution time of a method. If the method execution exceeds the time, the transaction is rolled back.
The unit is seconds, an integer value, and the default is -1. ( No modification is generally required )

Transaction propagation behavior : Control whether the business method has a transaction, and what kind of transaction it is.
The 7 propagation behaviors indicate how transactions are used between methods when your business method is called.

PROPAGATION_REQUIRED (commonly used, default )

The specified method must be executed within the transaction. If there is a transaction, it will be added to the current transaction


Always create a new transaction. If there is a transaction currently, the current transaction will be suspended until the new transaction is completed.


The specified method supports the current transaction, but if there is no current transaction, it can also be executed in a non-transactional manner.





2.3 When the transaction commits the transaction and rolls back the transaction

When your business method is executed successfully and no exception is thrown, when the method is executed, Spring commits the transaction after the method is executed. Transaction manager commit

When your business method throws a runtime exception or ERROR, spring performs a rollback and calls the rollback of the transaction manager.
The definition of runtime exception: RuntimeException and its subclasses are runtime exceptions.

​ For example: NullPointException, NumberFormatException

When your business method throws non-runtime exceptions, mainly the checked exceptions, submit the transaction.
Checked exceptions: exceptions that must be handled in your code. For example IOException, SQLException

2.4 Summary of spring affairs

  1. The management affairs is the affairs management and his realization class
  2. Spring's transaction is a unified model
  3. Specify the transaction manager implementation class to be used, use
  4. Specify which classes and which methods need to be added to the transaction function
  5. Specify the isolation level required by the method, propagation behavior, timeout

Need to specify for spring: the information of the class in the project, the name of the method, the transaction propagation behavior of the method

Three, two transaction processing solutions provided in the spring framework

There are two ways:

  1. Use Spring's transaction annotations to manage transactions (master)
  2. Use AspectJ's AOP configuration management transaction (master)

3.1 Use Spring's transaction annotations to manage transactions

Annotation scheme suitable for small and medium-sized projects.

The spring framework itself uses aop to implement the function of adding transactions to business methods, and uses @Transactional annotations to add transactions.
The @Transactional annotation is the spring framework's own annotation, placed above the public method, indicating that the current method has a transaction.
You can assign values ​​to the annotated attributes to indicate the specific isolation level, propagation behavior, abnormal information, etc.

Steps to use @Transactional :

Declare the transaction manager (to specify dataSource, that is, declare the data source before)

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

Turn on transaction annotation- driven driven at the end of tx (assignment of transaction manager id)

<tx:annotation-driven transaction-manager="transactionManager"/>

The service layer adds the @Transactional annotation to the public method that needs to open the transaction

     * rollbackFor:表示发生指定的异常一定回滚.
     * 处理逻辑是:
     * 1) spring框架会首先检查方法抛出的异常是不是在rollbackFor的属性值中
     * 如果异常在rollbackFor列表中,不管是什么类型的异常,一定回滚。
     * 2) 如果你的抛出的异常不在rollbackFor列表中,spring会判断异常是不是RuntimeException,
     * 如果是一定回滚。

//使用的是事务控制的默认值, 默认的传播行为是REQUIRED,默认的隔离级别DEFAULT
//    @Transactional(
//            propagation = Propagation.REQUIRED,
//            isolation = Isolation.DEFAULT,
//            readOnly = false,
//            rollbackFor = {NullPointerException.class,
//                    NotEnoughException.class}
//    )
public void buy(Integer goodId, Integer nums) {

Principle: Spring uses the aop mechanism to create the class proxy object where @Transactional is located, and add transaction functions to the method.

Before the execution of your business method, first open the transaction, submit or roll back the transaction after the business method, use the surround notification of aop

		 Object myAround(){
			  }catch(Exception e){

3.2 Use AspectJ's AOP configuration management transaction (master)

​ Suitable for large-scale projects, there are a lot of classes, methods, need a lot of configuration transactions, use the aspectj framework function,

​ Declare the transactions required by the class and method in the spring configuration file. In this way, business methods and transaction configuration are completely separated.

Implementation steps: implemented in the xml configuration file.

To use the aspectj framework, you need to add dependencies in the pom file



Declare transaction manager object

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

Configure transaction notification:

Declare the type of transaction required by the method (transaction properties of the configuration method [isolation level, propagation behavior, timeout])

        id:自定义名称,表示 <tx:advice>和</tx:advice>之间的配置内容
    <tx:advice id="myAdvice" transaction-manager="transactionManager">
            <!--<tx:method name=""/>表示要给剧痛的方法配置事务属性,method可以有多个,分别给不同的方法配置事务属性
                name:方法名称 , (1) 完整的方法名称,不带有包和类
                               (2) 方法可以使用通配符,*表示任意字符
                propagation: 传播行为,枚举值
                isolation: 隔离级别
                rollback: 你指定的异常类名,全限定类型,发生异常一定回滚
            <tx:method name="buy" propagation="REQUIRED" isolation="DEFAULT"

            <tx:method name="add*" propagation="REQUIRES_NEW"/>
            <tx:method name="modify*"/>
            <tx:method name="remove*"/>
            <tx:method name="*" propagation="SUPPORTS" read-only="true"/>

Configuration enhancer:

Specify to whom the configured transaction notification will be woven

            expression:切入点表达式,指定哪些类要使用事务 aspectj会创建代理对象
    <aop:pointcut id="servicePt" expression="execution(* *..service..*.*(..))"/>

    <aop:advisor advice-ref="myAdvice" pointcut-ref="servicePt"/>

Four, mind map

Insert picture description here