jpa transaction 回滚_我遇到的JPA中事务回滚的问题
在最近的項(xiàng)目中,做的是解析XML文件,解析過(guò)程中會(huì)有異常,比如:XML文件中節(jié)點(diǎn)的數(shù)據(jù)和與之對(duì)應(yīng)的數(shù)據(jù)庫(kù)的字段中數(shù)據(jù)的類(lèi)型不匹配;XML中數(shù)據(jù)長(zhǎng)度超過(guò)數(shù)據(jù)庫(kù)定義的長(zhǎng)度;有數(shù)據(jù)了的重復(fù)插入問(wèn)題;讀取節(jié)點(diǎn)出錯(cuò);XML文件路徑出錯(cuò)……會(huì)遇到很多異常
我的項(xiàng)目使用的是Spring Boot,Spring Data JPA 其中Spring已經(jīng)封裝好了事務(wù),在注解@Transactional中,自動(dòng)執(zhí)行事務(wù),出異常自動(dòng)回滾,但在使用的時(shí)候會(huì)遇到一些問(wèn)題:
在多個(gè)方法中使用@Transactional,其中一個(gè)方法運(yùn)行時(shí)候報(bào)錯(cuò),但是數(shù)據(jù)卻插進(jìn)去了,但是其他兩個(gè)方法沒(méi)有;有時(shí)候拋了異常,卻不會(huì)回滾;方法嵌套的時(shí)候執(zhí)行報(bào)錯(cuò)……
查閱了一些資料后,得知是沒(méi)有正確使用Spring的@Transactional。
下面借用我查到的別人的博客中的例子來(lái)說(shuō)明Spring的@Transactional到底怎么用:
1 @Service2 public classSysConfigService {3
4 @Autowired5 privateSysConfigRepository sysConfigRepository;6
7 publicSysConfigEntity getSysConfig(String keyName) {8 SysConfigEntity entity =sysConfigRepository.findOne(keyName);9 returnentity;10 }11
12 publicSysConfigEntity saveSysConfig(SysConfigEntity entity) {13
14 if(entity.getCreateTime()==null){15 entity.setCreateTime(newDate());16 }17
18 returnsysConfigRepository.save(entity);19
20 }21
22 @Transactional23 public void testSysConfig(SysConfigEntity entity) throwsException {24 //不會(huì)回滾
25 this.saveSysConfig(entity);26 throw new Exception("sysconfig error");27
28 }29
30 @Transactional(rollbackFor = Exception.class)31 public void testSysConfig1(SysConfigEntity entity) throwsException {32 //會(huì)回滾
33 this.saveSysConfig(entity);34 throw new Exception("sysconfig error");35
36 }37
38 @Transactional39 public void testSysConfig2(SysConfigEntity entity) throwsException {40 //會(huì)回滾
41 this.saveSysConfig(entity);42 throw new RuntimeException("sysconfig error");43
44 }45
46 @Transactional47 public void testSysConfig3(SysConfigEntity entity) throwsException {48 //事務(wù)仍然會(huì)被提交
49 this.testSysConfig4(entity);50 throw new Exception("sysconfig error");51 }52
53 @Transactional(rollbackFor = Exception.class)54 public void testSysConfig4(SysConfigEntity entity) throwsException {55
56 this.saveSysConfig(entity);57 }58
59
60
61 }
對(duì)于常用的Spring的@Transactional的總結(jié)如下:
1、異常在A方法內(nèi)拋出,則A方法就得加注解
2、多個(gè)方法嵌套調(diào)用,如果都有 @Transactional 注解,則產(chǎn)生事務(wù)傳遞,默認(rèn) Propagation.REQUIRED
3、如果注解上只寫(xiě) @Transactional 默認(rèn)只對(duì) RuntimeException 回滾,而非 Exception 進(jìn)行回滾
4、如果要對(duì) checked Exceptions 進(jìn)行回滾,則需要 @Transactional(rollbackFor = Exception.class)
創(chuàng)作挑戰(zhàn)賽新人創(chuàng)作獎(jiǎng)勵(lì)來(lái)咯,堅(jiān)持創(chuàng)作打卡瓜分現(xiàn)金大獎(jiǎng)總結(jié)
以上是生活随笔為你收集整理的jpa transaction 回滚_我遇到的JPA中事务回滚的问题的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: python redis 哨兵_Redi
- 下一篇: Ubuntu 查看磁盘空间 及目录容量