Spring Comments (nine) ------ Transaction Management

1. Introduction affairs

  Transaction (Transaction), generally refers to things to do or have done. The term is meant computer may access and update the database in a variety of program execution unit data items (unit).

  Here we take money out of an example to explain: for example, you go to the ATM machine to take 1000 dollars, roughly two steps: the first step to enter the password amount, bank cards and 1,000 yuan deducted; the second step from the ATM out of 1000 dollars . These two steps must be executed either perform or not. If the bank card was charged for the 1000 ATM money but if it fails, you will lose 1000 yuan; if the bank failed but ATM card deducting money but out of 1000, the bank will lose $ 1,000.

  How to ensure that this will not be a two-step process abnormal, while another execution success? Transaction is used to solve this problem. A transaction is a series of actions, which is integrated with a complete unit of work, these actions must be completed, if there is a failure, then the transaction is rolled back to the beginning, as if nothing had happened . In the enterprise application development, transaction management is essential techniques used to ensure the integrity and consistency of the data.

2, four characteristics of the transaction (ACID)

  ①, atomicity (Atomicity): the transaction is an atomic operation, a series of actions. Atomicity of transactions to ensure that actions are either completed or totally ineffective.

  ②, consistency (Consistency): Once the transaction is completed (regardless of success or failure), the system must ensure that its business model in a consistent state, but will not be part of the complete partial failure. In reality, the data should not be destroyed.

  ③, isolation (Isolation): There may be many transactions simultaneously process the same data, so that each open transaction should be isolated from other transactions, to prevent data corruption.

  ④, persistent (Durability): Once the transaction is completed, no matter what system error occurs, its results should not be affected, so you can recover from any system crashes. Under normal circumstances, the results of the transaction is written to persistent memory.

3, Spring transaction management core interface

As shown below: Let each of these three interfaces brief

4,  PlatformTransactionManager transaction manager

   Spring transaction manager interface is the org.springframework.transaction.PlatformTransactionManager, shown above, is not directly Spring Management, through this interface, such as Spring JDBC, Hibernate provides so a corresponding transaction manager for each platform, and It is to delegate responsibility to the transaction related to transaction management platform frameworks such as Hibernate or JTA persistence mechanism provided to achieve.

  We enter into PlatformTransactionManager interface to view source code:

  ①, TransactionStatus getTransaction (TransactionDefinition definition), the transaction manager through TransactionDefinition, access to "state of affairs", to manage affairs.

  ②, void commit (TransactionStatus status) submitted in accordance with state

  ③, void rollback (TransactionStatus status) according to the state rollback

  That provides a consistent programming model Spring transaction management across different transaction API, the specific mechanism by the corresponding transaction management platform to achieve each.

  For example, let's import transaction management to achieve two platforms: JDBC and Hibernate

Then we again see PlatformTransactionManager interfaces, you will find it more than a few implementation classes, as follows:

5, TransactionStatus state of affairs

  In the above PlatformTransactionManager interface, there is a method:

  TransactionStatus This method returns the object, and then acquires the program according to the transaction state objects returned, then the corresponding operation.

  The contents of this TransactionStatus interfaces are as follows:

This interface describes some of the processing services to provide simple control transaction execution and query transaction status method, at the time of rollback or commit the need to apply the corresponding state of affairs.

6, the basic transaction attributes defined TransactionDefinition

  上面讲到的事务管理器接口PlatformTransactionManager通过getTransaction(TransactionDefinition definition)方法来得到事务,这个方法里面的参数是TransactionDefinition类,这个类就定义了一些基本的事务属性。 

那么什么是事务属性呢?事务属性可以理解成事务的一些基本配置,描述了事务策略如何应用到方法上。事务属性包含了5个方面,如图所示:

TransactionDefinition 接口方法如下:

  一、传播行为:当事务方法被另一个事务方法调用时,必须指定事务应该如何传播。

    Spring 定义了如下七中传播行为,这里以A业务和B业务之间如何传播事务为例说明:

  ①、PROPAGATION_REQUIRED :required , 必须。默认值,A如果有事务,B将使用该事务;如果A没有事务,B将创建一个新的事务。

  ②、PROPAGATION_SUPPORTS:supports ,支持。A如果有事务,B将使用该事务;如果A没有事务,B将以非事务执行。

  ③、PROPAGATION_MANDATORY:mandatory ,强制。A如果有事务,B将使用该事务;如果A没有事务,B将抛异常。

  ④、PROPAGATION_REQUIRES_NEW :requires_new,必须新的。如果A有事务,将A的事务挂起,B创建一个新的事务;如果A没有事务,B创建一个新的事务。

  ⑤、PROPAGATION_NOT_SUPPORTED :not_supported ,不支持。如果A有事务,将A的事务挂起,B将以非事务执行;如果A没有事务,B将以非事务执行。

  ⑥、PROPAGATION_NEVER :never,从不。如果A有事务,B将抛异常;如果A没有事务,B将以非事务执行。

  ⑦、PROPAGATION_NESTED :nested ,嵌套。A和B底层采用保存点机制,形成嵌套事务。

 

  二、隔离级别:定义了一个事务可能受其他并发事务影响的程度。

  并发事务引起的问题:

    在典型的应用程序中,多个事务并发运行,经常会操作相同的数据来完成各自的任务。并发虽然是必须的,但可能会导致以下的问题。

    ①、脏读(Dirty reads)——脏读发生在一个事务读取了另一个事务改写但尚未提交的数据时。如果改写在稍后被回滚了,那么第一个事务获取的数据就是无效的。

    ②、不可重复读(Nonrepeatable read)——不可重复读发生在一个事务执行相同的查询两次或两次以上,但是每次都得到不同的数据时。这通常是因为另一个并发事务在两次查询期间进行了更新。

    ③、幻读(Phantom read)——幻读与不可重复读类似。它发生在一个事务(T1)读取了几行数据,接着另一个并发事务(T2)插入了一些数据时。在随后的查询中,第一个事务(T1)就会发现多了一些原本不存在的记录。

    注意:不可重复读重点是修改,而幻读重点是新增或删除。

 

  在 Spring 事务管理中,为我们定义了如下的隔离级别:

  ①、ISOLATION_DEFAULT:使用后端数据库默认的隔离级别

  ②、ISOLATION_READ_UNCOMMITTED:最低的隔离级别,允许读取尚未提交的数据变更,可能会导致脏读、幻读或不可重复读

  ③、ISOLATION_READ_COMMITTED:允许读取并发事务已经提交的数据,可以阻止脏读,但是幻读或不可重复读仍有可能发生

  ④、ISOLATION_REPEATABLE_READ:对同一字段的多次读取结果都是一致的,除非数据是被本身事务自己所修改,可以阻止脏读和不可重复读,但幻读仍有可能发生

  ⑤、ISOLATION_SERIALIZABLE:最高的隔离级别,完全服从ACID的隔离级别,确保阻止脏读、不可重复读以及幻读,也是最慢的事务隔离级别,因为它通常是通过完全锁定事务相关的数据库表来实现的

  上面定义的隔离级别,在 Spring 的 TransactionDefinition.class 中也分别用常量 -1,0,1,2,4,8表示。比如 ISOLATION_DEFAULT 的定义:

   

   三、只读

   这是事务的第三个特性,是否为只读事务。如果事务只对后端的数据库进行该操作,数据库可以利用事务的只读特性来进行一些特定的优化。通过将事务设置为只读,你就可以给数据库一个机会,让它应用它认为合适的优化措施。

  四、事务超时

  为了使应用程序很好地运行,事务不能运行太长的时间。因为事务可能涉及对后端数据库的锁定,所以长时间的事务会不必要的占用数据库资源。事务超时就是事务的一个定时器,在特定时间内事务如果没有执行完毕,那么就会自动回滚,而不是一直等待其结束。

  五、回滚规则

  事务五边形的最后一个方面是一组规则,这些规则定义了哪些异常会导致事务回滚而哪些不会。默认情况下,事务只有遇到运行期异常时才会回滚,而在遇到检查型异常时不会回滚(这一行为与EJB的回滚行为是一致的) 。但是你可以声明事务在遇到特定的检查型异常时像遇到运行期异常那样回滚。同样,你还可以声明事务遇到特定的异常不回滚,即使这些异常是运行期异常。

7、Spring 编程式事务和声明式事务的区别 

  编程式事务处理:所谓编程式事务指的是通过编码方式实现事务,允许用户在代码中精确定义事务的边界。即类似于JDBC编程实现事务管理。管理使用TransactionTemplate或者直接使用底层的PlatformTransactionManager。对于编程式事务管理,spring推荐使用TransactionTemplate。

  声明式事务处理:管理建立在AOP之上的。其本质是对方法前后进行拦截,然后在目标方法开始之前创建或者加入一个事务,在执行完目标方法之后根据执行情况提交或者回滚事务。声明式事务最大的优点就是不需要通过编程的方式管理事务,这样就不需要在业务逻辑代码中掺杂事务管理的代码,只需在配置文件中做相关的事务规则声明(或通过基于@Transactional注解的方式),便可以将事务规则应用到业务逻辑中。

  简单地说,编程式事务侵入到了业务代码里面,但是提供了更加详细的事务管理;而声明式事务由于基于AOP,所以既能起到事务管理的作用,又可以不影响业务代码的具体实现。

8、不用事务实现转账

  我们还是以转账为实例。不用事务看如何实现转账。在数据库中有如下表 account ,内容如下:

  有两个用户 Tom 和 Marry 。他们初始账户余额都为 10000。这时候我们进行如下业务:Tom 向 Marry 转账 1000 块。那么这在程序中可以分解为两个步骤:

  ①、Tom 的账户余额 10000 减少 1000 块,剩余 9000 块。

  ②、Marry 的账户余额 10000 增加 1000 块,变为 11000块。

  上面两个步骤要么都执行成功,要么都不执行。我们通过 TransactionTemplate 编程式事务来控制:

第一步:创建Java工程并导入相应的 jar 包(这里不用事务其实不需要这么多jar包,为了后面的讲解需要,我们一次性导入所有的jar包)

第二步:编写 Dao 层

    AccountDao 接口:

package com.ys.dao;
 
public interface AccountDao {
    /**
     * 汇款
     * @param outer 汇款人
     * @param money 汇款金额
     */
    public void out(String outer,int money);
     
    /**
     * 收款
     * @param inner 收款人
     * @param money 收款金额
     */
    public void in(String inner,int money);
 
}

  AccountDaoImpl 接口实现类

 

package com.ys.dao.impl;
 
import org.springframework.jdbc.core.support.JdbcDaoSupport;
 
import com.ys.dao.AccountDao;
 
public class AccountDaoImpl extends JdbcDaoSupport implements AccountDao {
 
    /**
     * 根据用户名减少账户金额
     */
    @Override
    public void out(String outer, int money) {
        this.getJdbcTemplate().update("update account set money = money - ? where username = ?",money,outer);
    }
 
    /**
     * 根据用户名增加账户金额
     */
    @Override
    public void in(String inner, int money) {
        this.getJdbcTemplate().update("update account set money = money + ? where username = ?",money,inner);
    }
 
}

  第三步:实现 Service 层

    AccountService 接口

package com.ys.service;
 
public interface AccountService {
     
    /**
     * 转账
     * @param outer 汇款人
     * @param inner 收款人
     * @param money 交易金额
     */
    public void transfer(String outer,String inner,int money);
 
}

  AccountServiceImpl 接口实现类

package com.ys.service.impl;
 
import com.ys.dao.AccountDao;
import com.ys.service.AccountService;
 
public class AccountServiceImpl implements AccountService{
 
    private AccountDao accountDao;
     
    public void setAccountDao(AccountDao accountDao) {
        this.accountDao = accountDao;
    }
    @Override
    public void transfer(String outer, String inner, int money) {
        accountDao.out(outer, money);
        accountDao.in(inner, money);
    }
 
}

  第四步:Spring 全局配置文件 applicationContext.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
                           http://www.springframework.org/schema/beans/spring-beans.xsd
                           http://www.springframework.org/schema/aop
                           http://www.springframework.org/schema/aop/spring-aop.xsd
                           http://www.springframework.org/schema/context
                           http://www.springframework.org/schema/context/spring-context.xsd">   
    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <property name="driverClass" value="com.mysql.jdbc.Driver"></property>
        <property name="jdbcUrl" value="jdbc:mysql://localhost:3306/test"></property>
        <property name="user" value="root"></property>
        <property name="password" value="root"></property>
    </bean>
     
    <bean id="accountDao" class="com.ys.dao.impl.AccountDaoImpl">
        <property name="dataSource" ref="dataSource"></property>
    </bean>
     
    <bean id="accountService" class="com.ys.service.impl.AccountServiceImpl">
        <property name="accountDao" ref="accountDao"></property>
    </bean>
</beans>

  第五步:测试

public class TransactionTest {
     
    @Test
    public void testNoTransaction(){
        ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
        AccountService account = (AccountService) context.getBean("accountService");
        //Tom 向 Marry 转账1000
        account.transfer("Tom", "Marry", 1000);
    }
 
}

第六步:查看数据库表 account

  上面的结果和我们想的一样,Tom 账户 money 减少了1000块。而 Marry 账户金额增加了1000块。

   这时候问题来了,比如在 Tom 账户 money 减少了1000块正常。而 Marry 账户金额增加时发生了异常,实际应用中比如断电(这里我们人为构造除数不能为0的异常),如下:

那么这时候我们执行测试程序,很显然会报错,那么数据库是什么情况呢?

数据库account :

我们发现,程序执行报错了,但是数据库 Tom 账户金额依然减少了 1000 块,但是 Marry 账户的金额却没有增加。这在实际应用中肯定是不允许的,那么如何解决呢?

 

9、编程式事务处理AccountServiceImpl 接口:实现转账(TransactionTemplate )

  上面转账的两步操作中间发生了异常,但是第一步依然在数据库中进行了增加操作。实际应用中不会允许这样的情况发生,所以我们这里用事务来进行管理。

  Dao 层不变,我们在 Service 层注入 TransactionTemplate 模板,因为是用模板来管理事务,所以模板需要注入事务管理器  DataSourceTransactionManager 。而事务管理器说到底还是用底层的JDBC在管理,所以我们需要在事务管理器中注入 DataSource。这几个步骤分别如下:

AccountServiceImpl 接口:

package com.ys.service.impl;
 
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.TransactionCallbackWithoutResult;
import org.springframework.transaction.support.TransactionTemplate;
 
import com.ys.dao.AccountDao;
import com.ys.service.AccountService;
 
public class AccountServiceImpl implements AccountService{
 
    private AccountDao accountDao;
    private TransactionTemplate transactionTemplate;
     
    public void setTransactionTemplate(TransactionTemplate transactionTemplate) {
        this.transactionTemplate = transactionTemplate;
    }
    public void setAccountDao(AccountDao accountDao) {
        this.accountDao = accountDao;
    }
    @Override
    public void transfer(final String outer,final String inner,final int money) {
        transactionTemplate.execute(new TransactionCallbackWithoutResult() {
            @Override
            protected void doInTransactionWithoutResult(TransactionStatus arg0) {
                accountDao.out(outer, money);
                //int i = 1/0;
                accountDao.in(inner, money);
            }
        });
    }
 
}

Spring 全局配置文件 applicationContext.xml:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
                           http://www.springframework.org/schema/beans/spring-beans.xsd
                           http://www.springframework.org/schema/aop
                           http://www.springframework.org/schema/aop/spring-aop.xsd
                           http://www.springframework.org/schema/context
                           http://www.springframework.org/schema/context/spring-context.xsd">   
    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <property name="driverClass" value="com.mysql.jdbc.Driver"></property>
        <property name="jdbcUrl" value="jdbc:mysql://localhost:3306/test"></property>
        <property name="user" value="root"></property>
        <property name="password" value="root"></property>
    </bean>
     
    <bean id="accountDao" class="com.ys.dao.impl.AccountDaoImpl">
        <property name="dataSource" ref="dataSource"></property>
    </bean>
     
    <bean id="accountService" class="com.ys.service.impl.AccountServiceImpl">
        <property name="accountDao" ref="accountDao"></property>
        <property name="transactionTemplate" ref="transactionTemplate"></property>
    </bean>
     
    <!-- 创建模板 -->
    <bean id="transactionTemplate" class="org.springframework.transaction.support.TransactionTemplate">
        <property name="transactionManager" ref="txManager"></property>
    </bean>
     
    <!-- 配置事务管理器 ,管理器需要事务,事务从Connection获得,连接从连接池DataSource获得 -->
    <bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"></property>
    </bean>
</beans>

测试文件保持不变,可以分两次测试,第一次两次操作没有发生异常,然后数据库正常改变了。第二次操作中间发生了异常,发现数据库内容没变。

如果大家有兴趣也可以试试底层的PlatformTransactionManager来进行事务管理,我这里给出主要代码:

//定义一个某个框架平台的TransactionManager,如JDBC、Hibernate
        DataSourceTransactionManager dataSourceTransactionManager =
                new DataSourceTransactionManager();
        dataSourceTransactionManager.setDataSource(this.getJdbcTemplate().getDataSource()); // 设置数据源
     
        DefaultTransactionDefinition transDef = new DefaultTransactionDefinition(); // 定义事务属性
        transDef.setPropagationBehavior(DefaultTransactionDefinition.PROPAGATION_REQUIRED); // 设置传播行为属性
        TransactionStatus status = dataSourceTransactionManager.getTransaction(transDef); // 获得事务状态
        try {
            // 数据库操作
            accountDao.out(outer, money);
            int i = 1/0;
            accountDao.in(inner, money);
             
            dataSourceTransactionManager.commit(status);// 提交
        } catch (Exception e) {
            dataSourceTransactionManager.rollback(status);// 回滚
        }

10、声明式事务处理实现转账(基于AOP的 xml 配置)  

  Dao 层和 Service 层与我们最先开始的不用事务实现转账保持不变。主要是 applicationContext.xml 文件变化了。

  我们在 applicationContext.xml 文件中配置 aop 自动生成代理,进行事务管理:

  ①、配置管理器

  ②、配置事务详情

  ③、配置 aop

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
                           http://www.springframework.org/schema/beans/spring-beans.xsd
                           http://www.springframework.org/schema/aop
                           http://www.springframework.org/schema/aop/spring-aop.xsd
                           http://www.springframework.org/schema/context
                           http://www.springframework.org/schema/context/spring-context.xsd
                           http://www.springframework.org/schema/tx
                           http://www.springframework.org/schema/tx/spring-tx.xsd">
                             
    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <property name="driverClass" value="com.mysql.jdbc.Driver"></property>
        <property name="jdbcUrl" value="jdbc:mysql://localhost:3306/test"></property>
        <property name="user" value="root"></property>
        <property name="password" value="root"></property>
    </bean>
     
    <bean id="accountDao" class="com.ys.dao.impl.AccountDaoImpl">
        <property name="dataSource" ref="dataSource"></property>
    </bean>
     
    <bean id="accountService" class="com.ys.service.impl.AccountServiceImpl">
        <property name="accountDao" ref="accountDao"></property>
    </bean>
     
    <!-- 1 事务管理器 -->
    <bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"></property>
    </bean>
     
    <!-- 2 事务详情(事务通知)  , 在aop筛选基础上,比如对ABC三个确定使用什么样的事务。例如:AC读写、B只读 等
        <tx:attributes> 用于配置事务详情(属性属性)
            <tx:method name=""/> 详情具体配置
                propagation 传播行为 , REQUIRED:必须;REQUIRES_NEW:必须是新的
                isolation 隔离级别
    -->
    <tx:advice id="txAdvice" transaction-manager="txManager">
        <tx:attributes>
            <tx:method name="transfer" propagation="REQUIRED" isolation="DEFAULT"/>
        </tx:attributes>
    </tx:advice>
     
    <!-- 3 AOP编程,利用切入点表达式从目标类方法中 确定增强的连接器,从而获得切入点 -->
    <aop:config>
        <aop:advisor advice-ref="txAdvice" pointcut="execution(* com.ys.service..*.*(..))"/>
    </aop:config>
</beans>

测试类这里我们就不描述了,也是分有异常和无异常进行测试,发现与预期结果是吻合的。

11、声明式事务处理实现转账(基于AOP的 注解 配置) 

  分为如下两步:

  ①、在applicationContext.xml 配置事务管理器,将并事务管理器交予spring

  ②、在目标类或目标方法添加注解即可 @Transactional

  首先在 applicationContext.xml 文件中配置如下:

<!-- 1 事务管理器 -->
    <bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"></property>
    </bean>
    <!-- 2 将管理器交予spring
        * transaction-manager 配置事务管理器
        * proxy-target-class
            true : 底层强制使用cglib 代理
    -->
    <tx:annotation-driven transaction-manager="txManager" proxy-target-class="true"/>

其次在目标类或者方法添加注解@Transactional。如果在类上添加,则说明类中的所有方法都添加事务,如果在方法上添加,则只有该方法具有事务。

package com.ys.service.impl;
 
import javax.annotation.Resource;
 
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;
 
import com.ys.dao.AccountDao;
import com.ys.service.AccountService;
 
@Transactional(propagation=Propagation.REQUIRED , isolation = Isolation.DEFAULT)
@Service("accountService")
public class AccountServiceImpl implements AccountService{
    @Resource(name="accountDao")
    private AccountDao accountDao;
     
    public void setAccountDao(AccountDao accountDao) {
        this.accountDao = accountDao;
    }
    @Override
    public void transfer(String outer, String inner, int money) {
        accountDao.out(outer, money);
        //int i = 1/0;
        accountDao.in(inner, money);
    }
 
}

 

Guess you like

Origin www.cnblogs.com/deityjian/p/11069822.html