Spring transaction management scheme and transaction manager and transaction control API

Table of contents

1. Business management plan

1. Modify the business layer code

2. Test

Second, the transaction manager

1 Introduction

2. Introduce constraints in the configuration file

3. Perform transaction configuration

3. Transaction control API

1. PlatformTransactionManager interface

2. TransactionDefinition interface

3. TransactionStatus interface

Related readings of previous columns & articles 

1. Maven series of columns

2. Mybatis series of columns

3. Spring series of columns 

 


1. Business management plan

        The bottom layer of declarative transactions adopts AOP technology, and manually adding transactions at the service layer can solve the problems mentioned in the previous article.

1. Modify the business layer code

        Add a SqlSessionTemplate object, let us try catch the business method, submit if there is no exception, and roll back if the exception is caught.

package com.example.service;

import com.example.dao.AccountDao;
import com.example.pojo.Account;
import org.mybatis.spring.SqlSessionTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

@Service
public class AccountService {
    @Autowired
    private AccountDao accountDao;

    @Autowired
    private SqlSessionTemplate sessionTemplate;

    /**
     *
     * @param id1 转出人id
     * @param id2 转入人id
     * @param price 金额
     */
    // 作用方法上时,该方法都将具有该类型事务的事务属性
    public void transfer(int id1,int id2, double price){

        try {
            // 转出人减少余额
            Account account1 = accountDao.findById(id1);
            account1.setBalance(account1.getBalance() - price);
            accountDao.update(account1);

            // 模拟程序出错
            int i = 1 / 0;

            // 转入人增加余额
            Account account2 = accountDao.findById(id2);
            account2.setBalance(account2.getBalance() + price);
            accountDao.update(account2);
            sessionTemplate.commit();
        }
        catch (Exception e){
            e.printStackTrace();
            sessionTemplate.rollback();
        }
    }
}

2. Test

 OK, you can see that the program is interrupted abnormally. Now watch what's going on in the database. 

        OK, you can see that Zhang San has not been deducted money here, so it is also possible to submit the transaction manually, but in this way we have too many try catches. Hence the transaction manager.

Second, the transaction manager

1 Introduction

        Spring relies on the transaction manager for transaction management. The transaction manager is a notification class. We set the cut point for the notification class as a service layer method to complete automatic transaction management. Since different technologies operate databases, the methods for performing transaction operations are different. For example: JDBC commits transaction is connection.commit(), MyBatis commits transaction is sqlSession.commit(), so Spring provides multiple transaction managers.

transaction manager name effect
org.springframework.jdbc.datasource.DataSourceTransactionManager A transaction manager for JDBC technology. Works with JDBC and MyBatis.
org.springframework.orm.hibernate3.HibernateTransactionManager For the transaction manager provided by the Hibernate framework. Works with the Hibernate framework.
org.springframework.orm.jpa.JpaTransactionManager The transaction manager provided for JPA technology. Applicable to JPA technology.
org.springframework.transaction.jta.JtaTransactionManager Spans multiple transaction management sources. It is suitable for implementing transaction control in two or more different data sources.

        We use MyBatis to operate the database, and then use DataSourceTransactionManager for transaction management.

2. Introduce constraints in the configuration file

xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd

3. Perform transaction configuration

Add configuration in the applicationContext.xml file

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

    <!-- 进行事务相关配置 -->
    <tx:advice id = "txAdvice">
        <tx:attributes>
            <!-- 代表所有方法 -->
            <tx:method name="*" />
        </tx:attributes>
    </tx:advice>

    <!-- 配置切面 -->
    <aop:config>
        <!-- 配置切点 -->
        <aop:pointcut id="pointcut" expression="execution(* com.example.service..*(..))"/>
        <!-- 配置通知 -->
        <aop:advisor advice-ref="txAdvice" pointcut-ref="pointcut"/>
    </aop:config>

3. Transaction control API

        All transaction managers implement the PlatformTransactionManager interface. Spring’s transaction control function is provided by three interfaces. These three interfaces are implemented by Spring. We rarely use them in development. We only need to understand their functions:

1. PlatformTransactionManager interface

PlatformTransactionManager is a transaction manager interface provided by Spring, and all transaction managers implement this interface. This interface provides three transaction operation methods:

  1. TransactionStatus getTransaction (TransactionDefinition definition): Get transaction status information.
  2. void commit (TransactionStatus status): transaction commit
  3. void rollback(TransactionStatus status): transaction rollback

2. TransactionDefinition interface

TransactionDefinition is the definition information object of the transaction, which has the following methods:

  1. String getName(): Get the transaction object name.
  2. int getIsolationLevel(): Get the isolation level of the transaction.
  3. int getPropagationBehavior(): Get the propagation behavior of the transaction.
  4. int getTimeout(): Get the timeout time of the transaction.
  5. boolean isReadOnly(): Gets whether the transaction is read-only.

3. TransactionStatus interface

TransactionStatus is the status interface of the transaction, which describes the status information of the transaction at a certain point in time. It has the following methods:

  1. void flush() refresh transaction
  2. boolean hasSavepoint() Gets whether there is a savepoint
  3. boolean isCompleted() Get whether the transaction is completed
  4. boolean isNewTransaction() Get whether it is a new transaction
  5. boolean isRollbackOnly() Get whether to roll back
  6. void setRollbackOnly() Set transaction rollback

Related readings of previous columns & articles 

     If you don’t know anything about the content of this issue, you can also go to see the content of previous issues. The following is a series of column articles such as Maven and Mybatis carefully crafted by bloggers in the past. Don’t miss it when you pass by! If it is helpful to you, please like it and bookmark it. Among them, some of the Spring columns are being updated, so they cannot be viewed, but they can be viewed after the bloggers have completed all the updates.

1. Maven series of columns

Maven Series Column Maven project development
Maven aggregation development [example detailed explanation --- 5555 words]

2. Mybatis series of columns

Mybatis series column MyBatis entry configuration
Mybatis entry case [super detailed]
MyBatis configuration file - detailed explanation of related tags
Mybatis fuzzy query - three methods of defining parameters and aggregation query, primary key backfill
Mybatis dynamic SQL query -- (attached actual combat case -- 8888 words -- 88 quality points)
Mybatis paging query - four ways to pass parameters
Mybatis first level cache and second level cache (with test method)
Mybatis decomposition query
Mybatis related query [attached actual combat case]
MyBatis annotation development --- realize addition, deletion, modification and dynamic SQL
MyBatis annotation development --- realize custom mapping relationship and associated query

3. Spring series of columns 

Spring series column Introduction to getting started with Spring IOC [custom container instance]
IOC uses Spring to implement detailed explanation with examples
The creation method, strategy, destruction timing, life cycle and acquisition method of Spring IOC objects
Introduction to Spring DI and Dependency Injection Method and Dependency Injection Type
Application of Spring IOC-related annotations——Part 1
Application of Spring IOC-related annotations——Part 2
Introduction to Spring AOP and related cases
Annotation, native Spring, and SchemaBased implement AOP in three ways [with detailed case]
Introduction to Spring affairs and related cases
Spring transaction management scheme and transaction manager and transaction control API
Spring transaction related configuration, propagation behavior, isolation level and annotation configuration declarative transaction

 

Guess you like

Origin blog.csdn.net/qq_53317005/article/details/131148647