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

当我的操作,涉及得到多个表,或者是多个sql语句的insert,update,delete。需要保证
  这些语句都是成功才能完成我的功能,或者都失败,保证操作是符合要求的。

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

  <!--声明式事务处理:和源代码完全分离-->
    <!--1.声明事务管理器对象-->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="myDataSource"/>
    </bean>

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

PROPAGATION_REQUIRES_NEW (commonly used)

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

PROPAGATION_SUPPORTS (commonly used)

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

PROPAGATION_MANDATORY

PROPAGATION_NESTED

PROPAGATION_NEVER

PROPAGATION_NOT_SUPPORTED

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"/>
    </bean>

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

<!--开启事务注解驱动,告诉spring使用注解管理事务,创建代理对象
              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}
//    )
@Transactional
@Override
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

 @Around("你要增加的事务功能的业务方法名称")
		 Object myAround(){
           开启事务,spring给你开启
			  try{
			     buy(1001,10);
				  spring的事务管理器.commit();
			  }catch(Exception e){
             spring的事务管理器.rollback();
			  }
			 
		 }

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

pom.xml

<!--aspectj依赖-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-aspects</artifactId>
            <version>5.2.15.RELEASE</version>
        </dependency>

Declare transaction manager object

  <!--声明式事务处理:和源代码完全分离-->
    <!--1.声明事务管理器对象-->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="myDataSource"/>
    </bean>

Configure transaction notification:

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

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

            <!--使用通配符,指定很多的方法-->
            <tx:method name="add*" propagation="REQUIRES_NEW"/>
            <!--指定修改方法-->
            <tx:method name="modify*"/>
            <!--指定删除方法-->
            <tx:method name="remove*"/>
            <!--查询方法,query,search,find-->
            <tx:method name="*" propagation="SUPPORTS" read-only="true"/>
        </tx:attributes>
    </tx:advice>

Configuration enhancer:

Specify to whom the configured transaction notification will be woven

<!--配置aop-->
<aop:config>
    <!--配置切入点表达式:指定哪些包中类,要使用事务,
            id:切入点表达式的名称,唯一值
            expression:切入点表达式,指定哪些类要使用事务 aspectj会创建代理对象
        -->
    <aop:pointcut id="servicePt" expression="execution(* *..service..*.*(..))"/>

    <!--配置增加器,关联adivce和pointcut
            advice-ref:通知,上面的tx:advice那里的配置
            pointcut-ref=切入点表达式
        -->
    <aop:advisor advice-ref="myAdvice" pointcut-ref="servicePt"/>
</aop:config>

Four, mind map

Insert picture description here