天天看点

Spring事务基础

我猜大概50%的java程序员(别问我怎么知道的,反正我就是,太失败了!!!)现在仅仅局限于一个@transactional注解或者在xml中配置事务相关的东西,然后除了事务级别之外,其他的事务知识可能是空白的。为了更加全面地学习,所以我就汇总一下spring事务的知识点,有什么不对或者补充的,大家记得留言告诉我哈。

关于事务的由来,我就不举例子了,很多人第一反应就是去银行存钱(然而我是用花呗的)的操作了。

事务的四大特性acid:

原子性(atomicity)

一致性(consistency)

隔离性(isolation)

持久性(durability)

(1)read uncommited:是最低的事务隔离级别,它允许另外一个事务可以看到这个事务未提交的数据。

(2)read commited:保证一个事物提交后才能被另外一个事务读取。另外一个事务不能读取该事物未提交的数据。

(3)repeatable read:这种事务隔离级别可以防止脏读,不可重复读。但是可能会出现幻象读。它除了保证一个事务不能被另外一个事务读取未提交的数据之外还避免了以下情况产生(不可重复读)。

(4)serializable:这是花费最高代价但最可靠的事务隔离级别。事务被处理为顺序执行。除了防止脏读,不可重复读之外,还避免了幻象读

说明:

a.脏读:指当一个事务正字访问数据,并且对数据进行了修改,而这种数据还没有提交到数据库中,这时,另外一个事务也访问这个数据,然后使用了这个数据。因为这个数据还没有提交那么另外一个事务读取到的这个数据我们称之为脏数据。依据脏数据所做的操作肯能是不正确的。

b.不可重复读:指在一个事务内,多次读同一数据。在这个事务还没有执行结束,另外一个事务也访问该同一数据,那么在第一个事务中的两次读取数据之间,由于第二个事务的修改第一个事务两次读到的数据可能是不一样的,这样就发生了在一个事物内两次连续读到的数据是不一样的,这种情况被称为是不可重复读。

c.幻象读:一个事务先后读取一个范围的记录,但两次读取的纪录数不同,我们称之为幻象读(两次执行同一条 select 语句会出现不同的结果,第二次读会增加一数据行,并没有说这两次执行是在同一个事务中)

@transactional注解估计大家都了解,那么我们先跟踪一下它的源码,发现了platformtransactionmanager这个接口类,具体的接口方法如下:

public interface platformtransactionmanager()...{     // 由transactiondefinition得到transactionstatus对象     transactionstatus gettransaction(transactiondefinition definition) throws transactionexception;     // 提交     void commit(transactionstatus status) throws transactionexception;     // 回滚     void rollback(transactionstatus status) throws transactionexception;     }

它就是定义了我们平时操作事务的三大步骤。具体实现由它的子类来实现,也就是如下图所示的关系:

Spring事务基础

(1)编程式事务管理对基于 pojo 的应用来说是唯一选择。我们需要在代码中调用begintransaction()、commit()、rollback()等事务管理相关的方法,这就是编程式事务管理。(学过java都会的吧,我就不啰嗦这个了。) (2)基于 transactionproxyfactorybean的声明式事务管理 (3)基于 @transactional 的声明式事务管理 (4)基于aspectj aop配置事务

具体实现如下:

import org.springframework.transaction.platformtransactionmanager; import org.springframework.transaction.transactionstatus; import org.springframework.transaction.support.defaulttransactiondefinition; //1、注入事务管理器对象 @autowired private platformtransactionmanager txmanager; //2、开启事务 transactionstatus status = txmanager.gettransaction(new defaulttransactiondefinition()); //3、提交 txmanager.commit(status); 4、回滚 txmanager.rollback(status);

使用场景:在springboot项目开发中,涉及到调用第三方接口,请求第三方接口成功但返回相关交易失败的话,需要删除插入表的某条数据,或更新别表中的表状态同时记录日志等,将第三方请求的实际完成情况返回给前端。

配置文件: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:p="http://www.springframework.org/schema/p"     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-3.0.xsd                         http://www.springframework.org/schema/context                         http://www.springframework.org/schema/context/spring-context-3.0.xsd                         http://www.springframework.org/schema/tx                         http://www.springframework.org/schema/tx/spring-tx-3.0.xsd                         http://www.springframework.org/schema/aop                         http://www.springframework.org/schema/aop/spring-aop-3.0.xsd">     <!-- 引用外部文件 db.properties读取数据库配置-->     <context:property-placeholder location="classpath:db.properties"/>     <!-- schemalocation后面两个命名空间是扫描该包必须有的 -->     <!-- 扫描com.sunline包以及所有子包,为所有加了注解的类创建bean -->     <context:component-scan base-package="com.sunline">     </context:component-scan>     <bean id="datasource"         class="org.apache.commons.dbcp.basicdatasource">         <property name="driverclassname"             value="${driverclassname}">         </property>         <property name="url"             value="${url}">         <property name="username" value="${username}"></property>         <property name="password" value="${password}"></property>     </bean>     <bean id="sessionfactory"         class="org.springframework.orm.hibernate3.localsessionfactorybean">         <property name="datasource">             <ref bean="datasource" />         <property name="hibernateproperties">             <props>                 <prop key="hibernate.dialect">                     org.hibernate.dialect.mysqldialect                 </prop>                 <prop key="dialect">                 <prop key="hibernate.hbm2ddl.auto">true</prop>                 <prop key="hibernate.show_sql">true</prop>             </props>         <property name="mappingresources">             <list>                 <value>com/sunline/entity/account.hbm.xml</value>             </list>    </bean>        <!-- 配置hibernate事务管理器 -->      <bean id="transactionmanager" class="org.springframework.orm.hibernate3.hibernatetransactionmanager">         <property name="sessionfactory" ref="sessionfactory" />        <!-- ==================================2.使用xml配置声明式的事务管理(原始方式)=============================================== -->     <!-- 配置业务层的代理 -->     <bean id="accountserviceproxy" class="org.springframework.transaction.interceptor.transactionproxyfactorybean">         <!-- 配置目标对象 -->         <property name="target" ref="accountbiztwo" />         <!-- 注入事务管理器 -->         <property name="transactionmanager" ref="transactionmanager"></property>         <!-- 注入事务的属性 -->         <property name="transactionattributes">                 <!--                     prop的格式:                         * propagation :事务的传播行为                         * isotation :事务的隔离级别                         * readonly :只读                         * -exception :发生哪些异常回滚事务                         * +exception :发生哪些异常不回滚事务                  -->                 <prop key="transfer">propagation_required,readonly</prop>                 <!-- <prop key="transfer">propagation_required,readonly</prop> -->                 <!-- <prop key="transfer">propagation_required,+java.lang.arithmeticexception</prop> --> </beans>

这个最简单,就暂时不细讲。

Spring事务基础

1)、创建工具类,用于开启事务,提交事务,会滚事务

import org.springframework.beans.factory.annotation.autowired; import org.springframework.context.annotation.scope; import org.springframework.jdbc.datasource.datasourcetransactionmanager; import org.springframework.stereotype.component; import org.springframework.transaction.interceptor.defaulttransactionattribute; //注入spring容器中 @component //创建为多例对象,放置多线程安全问题 @scope("prototype") public class aopaspectutil {     @autowired     private datasourcetransactionmanager manager; //注入spring的事务管理器    //事务拦截器     private transactionstatus transaction;     public transactionstatus begin() {         transaction = manager.gettransaction(new defaulttransactionattribute());//设置为默认事务隔离级别        //返回事务拦截器         return transaction;     public void commit() {        // 提交事务         manager.commit(transaction);     public void rollback() {        //回滚事务         manager.rollback(transaction); }

2)、定义注解

import java.lang.annotation.elementtype; import java.lang.annotation.retention; import java.lang.annotation.retentionpolicy; import java.lang.annotation.target; @target({elementtype.type,elementtype.method})//设置注解使用范围 @retention(retentionpolicy.runtime)//注解不仅被保存到class文件中,jvm加载class文件之后,仍然存在 public @interface mytransactional {

3)、自定义通知

使用注意,在针对事务管理方面,方法中不要去try{}catch(){},使用try,,catch后aop不能获取到异常信息,会导致出现异常后不能进行回滚,如果确实需要try,,,catch 可以再finally中加上transactionaspectsupport.currenttransactionstatus().setrollbackonly();由此段代码进行事务的回滚

import com.zbin.aop.mytransation.transactionutils; import org.aspectj.lang.proceedingjoinpoint; import org.aspectj.lang.annotation.afterthrowing; import org.aspectj.lang.annotation.around; import org.aspectj.lang.annotation.aspect; import org.springframework.transaction.interceptor.transactionaspectsupport; @aspect public class aoptransaction {     private transactionutils transactionutils;     @around("execution(* cn.xbmchina.service.userservice.add(..))")     public void around(proceedingjoinpoint proceedingjoinpoint) throws throwable {         //调用方法之前执行         system.out.println("开启事务");        transactionutils.begin();         proceedingjoinpoint.proceed();         //调用方法之后执行         system.out.println("提交事务");         transactionutils.commit();     @afterthrowing("execution(* cn.xbmchina.aop.service.userservice.add(..))")     public void afterthrowing() {         system.out.println("异常通知 ");         //获取当前事务进行回滚         //transactionaspectsupport.currenttransactionstatus().setrollbackonly();         transactionutils.rollback();

4)、测试

@mytransactional public void add() {     userdao.add("test001", 20);     int i = 1 / 0;     system.out.println("---------------------");     userdao.add("test002", 20);

事务传播行为(propagation behavior)指的就是当一个事务方法被另一个事务方法调用时,这个事务方法应该如何进行。

例如:methoda事务方法调用methodb事务方法时,methodb是继续在调用者methoda的事务中运行呢,还是为自己开启一个新事务运行,这就是由methodb的事务传播行为决定的。

Spring事务基础

看完还是觉得有点懵,那就一个个地为各位简单介绍一下呗。

如果存在一个事务,则支持当前事务。如果没有事务则开启一个新的事务。可以把事务想像成一个胶囊,在这个场景下方法b用的是方法a产生的胶囊(事务)。

@transactional(propagation = propagation.required) public void methoda() {  methodb(); // do something public void methodb() {     // do something

单独调用methodb方法时,因为当前上下文不存在事务,所以会开启一个新的事务。调用methoda方法时,因为当前上下文不存在事务,所以会开启一个新的事务。当执行到methodb时,methodb发现当前上下文有事务,因此就加入到当前事务中来。

如果存在一个事务,支持当前事务。如果没有事务,则非事务的执行。但是对于事务同步的事务管理器,propagation_supports与不使用事务有少许不同。

// 事务属性为supports @transactional(propagation = propagation.supports)

单纯的调用methodb时,methodb方法是非事务的执行的。当调用methda时,methodb则加入了methoda的事务中,事务地执行。

如果已经存在一个事务,支持当前事务。如果没有一个活动的事务,则抛出异常。

// 事务属性为mandatory @transactional(propagation = propagation.mandatory)

当单独调用methodb时,因为当前没有一个活动的事务,则会抛出异常throw new illegaltransactionstateexception(“transaction propagation ‘mandatory’ but no existing transaction found”);当调用methoda时,methodb则加入到methoda的事务中,事务地执行。

使用propagation_requires_new,需要使用 jtatransactionmanager作为事务管理器。它会开启一个新的事务。如果一个事务已经存在,则先将这个存在的事务挂起。

dosomethinga(); methodb(); dosomethingb(); // do something else // 事务属性为requires_new @transactional(propagation = propagation.requires_new)

当调用methoda();时,相当于如下代码

main(){     transactionmanager tm = null;     try{         //获得一个jta事务管理器         tm = gettransactionmanager();         tm.begin();//开启一个新的事务         transaction ts1 = tm.gettransaction();         dosomething();         tm.suspend();//挂起当前事务         try{             tm.begin();//重新开启第二个事务             transaction ts2 = tm.gettransaction();             methodb();             ts2.commit();//提交第二个事务         } catch(runtimeexception ex) {             ts2.rollback();//回滚第二个事务         } finally {             //释放资源         }         //methodb执行完后,恢复第一个事务         tm.resume(ts1);         dosomethingb();         ts1.commit();//提交第一个事务     } catch(runtimeexception ex) {         ts1.rollback();//回滚第一个事务     } finally {         //释放资源

在这里,我把ts1称为外层事务,ts2称为内层事务。从上面的代码可以看出,ts2与ts1是两个独立的事务,互不相干。ts2是否成功并不依赖于 ts1。如果methoda方法在调用methodb方法后的dosomethingb方法失败了,而methodb方法所做的结果依然被提交。而除了 methodb之外的其它代码导致的结果却被回滚了

propagation_not_supported 总是非事务地执行,并挂起任何存在的事务。使用propagation_not_supported,也需要使用jtatransactionmanager作为事务管理器。

Spring事务基础

总是非事务地执行,如果存在一个活动事务,则抛出异常。

Spring事务基础

示例:

methoda(){   dosomethinga();   methodb();   dosomethingb(); @transactional(propagation = propagation.newsted) methodb(){   ……

如果单独调用methodb方法,则按required属性执行。如果调用methoda方法,相当于下面的效果:

    connection con = null;     savepoint savepoint = null;         con = getconnection();         con.setautocommit(false);         dosomethinga();         savepoint = con2.setsavepoint();             con.rollback(savepoint);         con.commit();         con.rollback();

当methodb方法调用之前,调用setsavepoint方法,保存当前的状态到savepoint。如果methodb方法调用失败,则恢复到之前保存的状态。但是需要注意的是,这时的事务并没有进行提交,如果后续的代码(dosomethingb()方法)调用失败,则回滚包括methodb方法的所有操作。嵌套事务一个非常重要的概念就是内层事务依赖于外层事务。外层事务失败时,会回滚内层事务所做的动作。而内层事务操作失败并不会引起外层事务的回滚。

特别地:propagation_requires_new 和 propagation_nested 的最大区别在于, propagation_requires_new 完全是一个新的事务, 而 propagation_nested 则是外部事务的子事务, 如果外部事务 commit, 嵌套事务也会被 commit, 这个规则同样适用于 roll back.

以上都是一个数据源的情况下的事务处理,那你有没有想过如果多个数据源的情况下,这个事务如何得到保证呢?还请留意下次更新【spring多数据源事务】

Spring事务基础