日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

jpa transaction 回滚_我遇到的JPA中事务回滚的问题

發(fā)布時間:2025/3/8 编程问答 27 豆豆
生活随笔 收集整理的這篇文章主要介紹了 jpa transaction 回滚_我遇到的JPA中事务回滚的问题 小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.

在最近的項目中,做的是解析XML文件,解析過程中會有異常,比如:XML文件中節(jié)點的數(shù)據(jù)和與之對應(yīng)的數(shù)據(jù)庫的字段中數(shù)據(jù)的類型不匹配;XML中數(shù)據(jù)長度超過數(shù)據(jù)庫定義的長度;有數(shù)據(jù)了的重復(fù)插入問題;讀取節(jié)點出錯;XML文件路徑出錯……會遇到很多異常

我的項目使用的是Spring Boot,Spring Data JPA 其中Spring已經(jīng)封裝好了事務(wù),在注解@Transactional中,自動執(zhí)行事務(wù),出異常自動回滾,但在使用的時候會遇到一些問題:

在多個方法中使用@Transactional,其中一個方法運行時候報錯,但是數(shù)據(jù)卻插進(jìn)去了,但是其他兩個方法沒有;有時候拋了異常,卻不會回滾;方法嵌套的時候執(zhí)行報錯……

查閱了一些資料后,得知是沒有正確使用Spring的@Transactional。

下面借用我查到的別人的博客中的例子來說明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 //不會回滾

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 //會回滾

33 this.saveSysConfig(entity);34 throw new Exception("sysconfig error");35

36 }37

38 @Transactional39 public void testSysConfig2(SysConfigEntity entity) throwsException {40 //會回滾

41 this.saveSysConfig(entity);42 throw new RuntimeException("sysconfig error");43

44 }45

46 @Transactional47 public void testSysConfig3(SysConfigEntity entity) throwsException {48 //事務(wù)仍然會被提交

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 }

對于常用的Spring的@Transactional的總結(jié)如下:

1、異常在A方法內(nèi)拋出,則A方法就得加注解

2、多個方法嵌套調(diào)用,如果都有 @Transactional 注解,則產(chǎn)生事務(wù)傳遞,默認(rèn) Propagation.REQUIRED

3、如果注解上只寫 @Transactional 默認(rèn)只對 RuntimeException 回滾,而非 Exception 進(jìn)行回滾

4、如果要對 checked Exceptions 進(jìn)行回滾,則需要 @Transactional(rollbackFor = Exception.class)

創(chuàng)作挑戰(zhàn)賽新人創(chuàng)作獎勵來咯,堅持創(chuàng)作打卡瓜分現(xiàn)金大獎

總結(jié)

以上是生活随笔為你收集整理的jpa transaction 回滚_我遇到的JPA中事务回滚的问题的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。