相信每个人都被问过无数次Spring声明式事务的隔离级别和传播机制吧!今天我也来说说这两个东西.
加入一个小插曲,
一天电话里有人问我声明式事务隔离级别有哪几种,
我就回答了7种,
他问我Spring的版本,
我回答为3.0。
他说那应该是2.5的,3.0好像变少了。
我回答这个没有确认过。后来我就google了一下,没发现什么痕迹说明事务的隔离级别变少了,也查了下官方文档,也没有相关的说明。索性在github上clone一下Spring的源码,看看源码中有几种就是几种了呗。
后来想想那天他那么问我完全可能是一个坑啊,因为交谈的过程中挖过至少两个坑了。再者说,Spring要向下兼容的,如果少了怎么处理呢?当然这两点都是我自己的猜测。
在Spring中,声明式事务是用事务参数来定义的。一个事务参数就是对事务策略应该如何应用到某个方法的一段描述,如下图所示一个事务参数共有5个方面组成:
事务的第一个方面是传播行为。传播行为定义关于客户端和被调用方法的事务边界。Spring定义了7中传播行为。
传播行为 意义 PROPAGATION_MANDATORY 表示该方法必须运行在一个事务中。如果当前没有事务正在发生,将抛出一个异常 PROPAGATION_NESTED 表示如果当前正有一个事务在进行中,则该方法应当运行在一个嵌套式事务中。被嵌套的事务可以独立于封装事务进行提交或回滚。如果封装事务不存在,行为就像PROPAGATION_REQUIRES一样。 PROPAGATION_NEVER 表示当前的方法不应该在一个事务中运行。如果一个事务正在进行,则会抛出一个异常。 PROPAGATION_NOT_SUPPORTED 表示该方法不应该在一个事务中运行。如果一个现有事务正在进行中,它将在该方法的运行期间被挂起。 PROPAGATION_SUPPORTS 表示当前方法不需要事务性上下文,但是如果有一个事务已经在运行的话,它也可以在这个事务里运行。 PROPAGATION_REQUIRES_NEW 表示当前方法必须在它自己的事务里运行。一个新的事务将被启动,而且如果有一个现有事务在运行的话,则将在这个方法运行期间被挂起。 PROPAGATION_REQUIRES 表示当前方法必须在一个事务中运行。如果一个现有事务正在进行中,该方法将在那个事务中运行,否则就要开始一个新事务。传播规则回答了这样一个问题,就是一个新的事务应该被启动还是被挂起,或者是一个方法是否应该在事务性上下文中运行。
声明式事务的第二个方面是隔离级别。隔离级别定义一个事务可能受其他并发事务活动活动影响的程度。另一种考虑一个事务的隔离级别的方式,是把它想象为那个事务对于事物处理数据的自私程度。
在一个典型的应用程序中,多个事务同时运行,经常会为了完成他们的工作而操作同一个数据。并发虽然是必需的,但是会导致一下问题:
脏读(Dirtyread)--脏读发生在一个事务读取了被另一个事务改写但尚未提交的数据时。如果这些改变在稍后被回滚了,那么第一个事务读取的数据就会是无效的。 不可重复读(Nonrepeatableread)--不可重复读发生在一个事务执行相同的查询两次或两次以上,但每次查询结果都不相同时。这通常是由于另一个并发事务在两次查询之间更新了数据。 幻影读(Phantomreads)--幻影读和不可重复读相似。当一个事务(T1)读取几行记录后,另一个并发事务(T2)插入了一些记录时,幻影读就发生了。在后来的查询中,第一个事务(T1)就会发现一些原来没有的额外记录。在理想状态下,事务之间将完全隔离,从而可以防止这些问题发生。然而,完全隔离会影响性能,因为隔离经常牵扯到锁定在数据库中的记录(而且有时是锁定完整的数据表)。侵占性的锁定会阻碍并发,要求事务相互等待来完成工作。
考虑到完全隔离会影响性能,而且并不是所有应用程序都要求完全隔离,所以有时可以在事务隔离方面灵活处理。因此,就会有好几个隔离级别。
隔离级别 含义 ISOLATION_DEFAULT 使用后端数据库默认的隔离级别。 ISOLATION_READ_UNCOMMITTED 允许读取尚未提交的更改。可能导致脏读、幻影读或不可重复读。 ISOLATION_READ_COMMITTED 允许从已经提交的并发事务读取。可防止脏读,但幻影读和不可重复读仍可能会发生。 ISOLATION_REPEATABLE_READ 对相同字段的多次读取的结果是一致的,除非数据被当前事务本身改变。可防止脏读和不可重复读,但幻影读仍可能发生。 ISOLATION_SERIALIZABLE 完全服从ACID的隔离级别,确保不发生脏读、不可重复读和幻影读。这在所有隔离级别中也是最慢的,因为它通常是通过完全锁定当前事务所涉及的数据表来完成的。声明式事务的第三个特性是它是否是一个只读事务。如果一个事务只对后端数据库执行读操作,那么该数据库就可能利用那个事务的只读特性,采取某些优化措施。通过把一个事务声明为只读,可以给后端数据库一个机会来应用那些它认为合适的优化措施。由于只读的优化措施是在一个事务启动时由后端数据库实施的,因此,只有对于那些具有可能启动一个新事务的传播行为(PROPAGATION_REQUIRES_NEW、PROPAGATION_REQUIRED、ROPAGATION_NESTED)的方法来说,将事务声明为只读才有意义。
此外,如果使用Hibernate作为持久化机制,那么把一个事务声明为只读,将使Hibernate的flush模式被设置为FLUSH_NEVER。这就告诉Hibernate避免和数据库进行不必要的对象同步,从而把所有更新延迟到事务的结束。
为了使一个应用程序很好地执行,它的事务不能运行太长时间。因此,声明式事务的下一个特性就是它的超时。
假设事务的运行时间变得格外的长,由于事务可能涉及对后端数据库的锁定,所以长时间运行的事务会不必要地占用数据库资源。这时就可以声明一个事务在特定秒数后自动回滚,不必等它自己结束。
由于超时时钟在一个事务启动的时候开始的,因此,只有对于那些具有可能启动一个新事务的传播行为(PROPAGATION_REQUIRES_NEW、PROPAGATION_REQUIRED、ROPAGATION_NESTED)的方法来说,声明事务超时才有意义。
事务五边形的对后一个边是一组规则,它们定义哪些异常引起回滚,哪些不引起。在默认设置下,事务只在出现运行时异常(runtimeexception)时回滚,而在出现受检查异常(checkedexception)时不回滚(这一行为和EJB中的回滚行为是一致的)。
不过,也可以声明在出现特定受检查异常时像运行时异常一样回滚。同样,也可以声明一个事务在出现特定的异常时不回滚,即使那些异常是运行时一场。
标题是只有事务的隔离级别和传播机制,却顺带这把声明式事务的五个特性都讲述了一遍。:)
文章开头说过查看Spring中事务的源码来确认3.0版本及之后事务的传播机制是否减少了,其实在TransactionDefinition这个接口中定义了事务的隔离级别、传播机制、只读以及超时相关的全部信息。源码如下,感兴趣的可以自己对照一下,看看英文注释。
/* *Copyright2002-2010theoriginalauthororauthors. * *LicensedundertheApacheLicense,Version2.0(the"License"); *youmaynotusethisfileexceptincompliancewiththeLicense. *YoumayobtainacopyoftheLicenseat * *http://www.apache.org/licenses/LICENSE-2.0 * *Unlessrequiredbyapplicablelaworagreedtoinwriting,software *distributedundertheLicenseisdistributedonan"ASIS"BASIS, *WITHOUTWARRANTIESORCONDITIONSOFANYKIND,eitherexpressorimplied. *SeetheLicenseforthespecificlanguagegoverningpermissionsand *limitationsundertheLicense. */ packageorg.springframework.transaction; importjava.sql.Connection; /** *InterfacethatdefinesSpring-complianttransactionproperties. *BasedonthepropagationbehaviordefinitionsanalogoustoEJBCMTattributes. * *<p>Notethatisolationlevelandtimeoutsettingswillnotgetappliedunless *anactualnewtransactiongetsstarted.Asonly{@link#PROPAGATION_REQUIRED}, *{@link#PROPAGATION_REQUIRES_NEW}and{@link#PROPAGATION_NESTED}cancause *that,itusuallydoesntmakesensetospecifythosesettingsinothercases. *Furthermore,beawarethatnotalltransactionmanagerswillsupportthose *advancedfeaturesandthusmightthrowcorrespondingexceptionswhengiven *non-defaultvalues. * *<p>The{@link#isReadOnly()read-onlyflag}appliestoanytransactioncontext, *whetherbackedbyanactualresourcetransactionoroperatingnon-transactionally *attheresourcelevel.Inthelattercase,theflagwillonlyapplytomanaged *resourceswithintheapplication,suchasaHibernate<code>Session</code>. * *@authorJuergenHoeller *@since08.05.2003 *@seePlatformTransactionManager#getTransaction(TransactionDefinition) *@seeorg.springframework.transaction.support.DefaultTransactionDefinition *@seeorg.springframework.transaction.interceptor.TransactionAttribute */ publicinterfaceTransactionDefinition{ /** *Supportacurrenttransaction;createanewoneifnoneexists. *AnalogoustotheEJBtransactionattributeofthesamename. *<p>Thisistypicallythedefaultsettingofatransactiondefinition, *andtypicallydefinesatransactionsynchronizationscope. */ intPROPAGATION_REQUIRED=0; /** *Supportacurrenttransaction;executenon-transactionallyifnoneexists. *AnalogoustotheEJBtransactionattributeofthesamename. *<p><b>NOTE:</b>Fortransactionmanagerswithtransactionsynchronization, *<code>PROPAGATION_SUPPORTS</code>isslightlydifferentfromnotransaction *atall,asitdefinesatransactionscopethatsynchronizationmightapplyto. *Asaconsequence,thesameresources(aJDBC<code>Connection</code>,a *Hibernate<code>Session</code>,etc)willbesharedfortheentirespecified *scope.Notethattheexactbehaviordependsontheactualsynchronization *configurationofthetransactionmanager! *<p>Ingeneral,use<code>PROPAGATION_SUPPORTS</code>withcare!Inparticular,do *notrelyon<code>PROPAGATION_REQUIRED</code>or<code>PROPAGATION_REQUIRES_NEW</code> *<i>within</i>a<code>PROPAGATION_SUPPORTS</code>scope(whichmayleadto *synchronizationconflictsatruntime).Ifsuchnestingisunavoidable,makesure *toconfigureyourtransactionmanagerappropriately(typicallyswitchingto *"synchronizationonactualtransaction"). *@seeorg.springframework.transaction.support.AbstractPlatformTransactionManager#setTransactionSynchronization *@seeorg.springframework.transaction.support.AbstractPlatformTransactionManager#SYNCHRONIZATION_ON_ACTUAL_TRANSACTION */ intPROPAGATION_SUPPORTS=1; /** *Supportacurrenttransaction;throwanexceptionifnocurrenttransaction *exists.AnalogoustotheEJBtransactionattributeofthesamename. *<p>Notethattransactionsynchronizationwithina<code>PROPAGATION_MANDATORY</code> *scopewillalwaysbedrivenbythesurroundingtransaction. */ intPROPAGATION_MANDATORY=2; /** *Createanewtransaction,suspendingthecurrenttransactionifoneexists. *AnalogoustotheEJBtransactionattributeofthesamename. *<p><b>NOTE:</b>Actualtransactionsuspensionwillnotworkout-of-the-box *onalltransactionmanagers.Thisinparticularappliesto *{@linkorg.springframework.transaction.jta.JtaTransactionManager}, *whichrequiresthe<code>javax.transaction.TransactionManager</code> *tobemadeavailableittoit(whichisserver-specificinstandardJ2EE). *<p>A<code>PROPAGATION_REQUIRES_NEW</code>scopealwaysdefinesitsown *transactionsynchronizations.Existingsynchronizationswillbesuspended *andresumedappropriately. *@seeorg.springframework.transaction.jta.JtaTransactionManager#setTransactionManager */ intPROPAGATION_REQUIRES_NEW=3; /** *Donotsupportacurrenttransaction;ratheralwaysexecutenon-transactionally. *AnalogoustotheEJBtransactionattributeofthesamename. *<p><b>NOTE:</b>Actualtransactionsuspensionwillnotworkout-of-the-box *onalltransactionmanagers.Thisinparticularappliesto *{@linkorg.springframework.transaction.jta.JtaTransactionManager}, *whichrequiresthe<code>javax.transaction.TransactionManager</code> *tobemadeavailableittoit(whichisserver-specificinstandardJ2EE). *<p>Notethattransactionsynchronizationis<i>not</i>availablewithina *<code>PROPAGATION_NOT_SUPPORTED</code>scope.Existingsynchronizations *willbesuspendedandresumedappropriately. *@seeorg.springframework.transaction.jta.JtaTransactionManager#setTransactionManager */ intPROPAGATION_NOT_SUPPORTED=4; /** *Donotsupportacurrenttransaction;throwanexceptionifacurrenttransaction *exists.AnalogoustotheEJBtransactionattributeofthesamename. *<p>Notethattransactionsynchronizationis<i>not</i>availablewithina *<code>PROPAGATION_NEVER</code>scope. */ intPROPAGATION_NEVER=5; /** *Executewithinanestedtransactionifacurrenttransactionexists, *behavelike{@link#PROPAGATION_REQUIRED}else.Thereisnoanalogous *featureinEJB. *<p><b>NOTE:</b>Actualcreationofanestedtransactionwillonlyworkon *specifictransactionmanagers.Outofthebox,thisonlyappliestotheJDBC *{@linkorg.springframework.jdbc.datasource.DataSourceTransactionManager} *whenworkingonaJDBC3.0driver.SomeJTAprovidersmightsupport *nestedtransactionsaswell. *@seeorg.springframework.jdbc.datasource.DataSourceTransactionManager */ intPROPAGATION_NESTED=6; /** *Usethedefaultisolationleveloftheunderlyingdatastore. *AllotherlevelscorrespondtotheJDBCisolationlevels. *@seejava.sql.Connection */ intISOLATION_DEFAULT=-1; /** *Indicatesthatdirtyreads,non-repeatablereadsandphantomreads *canoccur. *<p>Thislevelallowsarowchangedbyonetransactiontobereadbyanother *transactionbeforeanychangesinthatrowhavebeencommitted(a"dirtyread"). *Ifanyofthechangesarerolledback,thesecondtransactionwillhave *retrievedaninvalidrow. *@seejava.sql.Connection#TRANSACTION_READ_UNCOMMITTED */ intISOLATION_READ_UNCOMMITTED=Connection.TRANSACTION_READ_UNCOMMITTED; /** *Indicatesthatdirtyreadsareprevented;non-repeatablereadsand *phantomreadscanoccur. *<p>Thislevelonlyprohibitsatransactionfromreadingarow *withuncommittedchangesinit. *@seejava.sql.Connection#TRANSACTION_READ_COMMITTED */ intISOLATION_READ_COMMITTED=Connection.TRANSACTION_READ_COMMITTED; /** *Indicatesthatdirtyreadsandnon-repeatablereadsareprevented; *phantomreadscanoccur. *<p>Thislevelprohibitsatransactionfromreadingarowwithuncommittedchanges *init,anditalsoprohibitsthesituationwhereonetransactionreadsarow, *asecondtransactionalterstherow,andthefirsttransactionre-readstherow, *gettingdifferentvaluesthesecondtime(a"non-repeatableread"). *@seejava.sql.Connection#TRANSACTION_REPEATABLE_READ */ intISOLATION_REPEATABLE_READ=Connection.TRANSACTION_REPEATABLE_READ; /** *Indicatesthatdirtyreads,non-repeatablereadsandphantomreads *areprevented. *<p>Thislevelincludestheprohibitionsin{@link#ISOLATION_REPEATABLE_READ} *andfurtherprohibitsthesituationwhereonetransactionreadsallrowsthat *satisfya<code>WHERE</code>condition,asecondtransactioninsertsarow *thatsatisfiesthat<code>WHERE</code>condition,andthefirsttransaction *re-readsforthesamecondition,retrievingtheadditional"phantom"row *inthesecondread. *@seejava.sql.Connection#TRANSACTION_SERIALIZABLE */ intISOLATION_SERIALIZABLE=Connection.TRANSACTION_SERIALIZABLE; /** *Usethedefaulttimeoutoftheunderlyingtransactionsystem, *ornoneiftimeoutsarenotsupported. */ intTIMEOUT_DEFAULT=-1; /** *Returnthepropagationbehavior. *<p>Mustreturnoneofthe<code>PROPAGATION_XXX</code>constants *definedon{@linkTransactionDefinitionthisinterface}. *@returnthepropagationbehavior *@see#PROPAGATION_REQUIRED *@seeorg.springframework.transaction.support.TransactionSynchronizationManager#isActualTransactionActive() */ intgetPropagationBehavior(); /** *Returntheisolationlevel. *<p>Mustreturnoneofthe<code>ISOLATION_XXX</code>constants *definedon{@linkTransactionDefinitionthisinterface}. *<p>Onlymakessenseincombinationwith{@link#PROPAGATION_REQUIRED} *or{@link#PROPAGATION_REQUIRES_NEW}. *<p>Notethatatransactionmanagerthatdoesnotsupportcustomisolationlevels *willthrowanexceptionwhengivenanyotherlevelthan{@link#ISOLATION_DEFAULT}. *@returntheisolationlevel */ intgetIsolationLevel(); /** *Returnthetransactiontimeout. *<p>Mustreturnanumberofseconds,or{@link#TIMEOUT_DEFAULT}. *<p>Onlymakessenseincombinationwith{@link#PROPAGATION_REQUIRED} *or{@link#PROPAGATION_REQUIRES_NEW}. *<p>Notethatatransactionmanagerthatdoesnotsupporttimeoutswillthrow *anexceptionwhengivenanyothertimeoutthan{@link#TIMEOUT_DEFAULT}. *@returnthetransactiontimeout */ intgetTimeout(); /** *Returnwhethertooptimizeasaread-onlytransaction. *<p>Theread-onlyflagappliestoanytransactioncontext,whether *backedbyanactualresourcetransaction *({@link#PROPAGATION_REQUIRED}/{@link#PROPAGATION_REQUIRES_NEW})or *operatingnon-transactionallyattheresourcelevel *({@link#PROPAGATION_SUPPORTS}).Inthelattercase,theflagwill *onlyapplytomanagedresourceswithintheapplication,suchasa *Hibernate<code>Session</code>. *<p>Thisjustservesasahintfortheactualtransactionsubsystem; *itwill<i>notnecessarily</i>causefailureofwriteaccessattempts. *Atransactionmanagerwhichcannotinterprettheread-onlyhintwill *<i>not</i>throwanexceptionwhenaskedforaread-onlytransaction. *@return<code>true</code>ifthetransactionistobeoptimizedasread-only *@seeorg.springframework.transaction.support.TransactionSynchronization#beforeCommit(boolean) *@seeorg.springframework.transaction.support.TransactionSynchronizationManager#isCurrentTransactionReadOnly() */ booleanisReadOnly(); /** *Returnthenameofthistransaction.Canbe<code>null</code>. *<p>Thiswillbeusedasthetransactionnametobeshownina *transactionmonitor,ifapplicable(forexample,WebLogics). *<p>IncaseofSpringsdeclarativetransactions,theexposednamewillbe *the<code>fully-qualifiedclassname+"."+methodname</code>(bydefault). *@returnthenameofthistransaction *@seeorg.springframework.transaction.interceptor.TransactionAspectSupport *@seeorg.springframework.transaction.support.TransactionSynchronizationManager#getCurrentTransactionName() */ StringgetName(); }还是觉得不安心,发两张图证明隔离级别和传播机制:
eclipse中给出的关于传播机制的智能提示截图 eclipse中给出的关于隔离级别的智能提示截图本文内容总结:声明式事务,传播行为,隔离级别,只读,事务超时,回滚规则,扩展阅读,
原文链接:https://www.cnblogs.com/zhishan/p/3195219.html