Spring注解式声明事务相关问题

以下整理自己在使用Spring(3.1.1)注解式声明事务遇到的相关问题。

1、方法的访问权限只有在public时,@Transactional才会生效。

引用

摘自http://docs.spring.io/spring/docs/3.2.12.RELEASE/spring-framework-reference/htmlsingle/

Methodvisibilityand@Transactional

Whenusingproxies,youshouldapplythe@Transactionalannotationonlytomethodswithpublicvisibility.Ifyoudoannotateprotected,privateorpackage-visiblemethodswiththe@Transactionalannotation,noerrorisraised,buttheannotatedmethoddoesnotexhibittheconfiguredtransactionalsettings.ConsidertheuseofAspectJ(seebelow)ifyouneedtoannotatenon-publicmethods.

2、同一个类中都声明@Transactional的方法调用,第二个方法的@Transactional不会生效。

引用

摘自http://docs.spring.io/spring/docs/3.2.12.RELEASE/spring-framework-reference/htmlsingle/

Inproxymode(whichisthedefault),onlyexternalmethodcallscominginthroughtheproxyareintercepted.Thismeansthatself-invocation,ineffect,amethodwithinthetargetobjectcallinganothermethodofthetargetobject,willnotleadtoanactualtransactionatruntimeeveniftheinvokedmethodismarkedwith@Transactional.

3、嵌套事务(子事务以REQUIRES_NEW方式)造成数据库死锁

引用

摘自http://stackoverflow.com/questions/17747906/getting-deadlock-found-when-trying-to-get-lock-try-restarting-transaction

MySQL'sInnoDBenginesportsrow-levellocking,whichcanleadtodeadlocksevenwhenyourcodeisinsertingorupdatingasinglerow(speciallyifthereareseveralindexesonthetablebeingupdated).Yourbestbetistodesignthecodearoundthisinordertoretryatransactionifitfailsduetoadeadlock.SomeusefulinfoaboutMySQLdeadlockdiagnoseandpossibleworkaroundsisavailablehere.

AninterestingimplementationofdeadlockretryviaAOPinSpringisavailablehere.Thiswayyoujustneedtoaddtheannotationtothemethodyouwanttoretryincaseofdeadlock.

4、在事务提交\事务回滚之后,处理一些事情。

// 在业务代码中,调用此代码
TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronizationAdapter(){
	// 重写afterCommit或者afterCompletion
    // 在事务提交\事务回滚之后,就会执行
});

相关推荐