Spring事務管理之如何處理刪除操作與事務回滾
引言
在實際開發(fā)中,事務管理是保證數據一致性的核心機制之一。特別是在涉及數據庫刪除操作時,如何正確處理刪除失敗、并發(fā)沖突等場景,是每個開發(fā)者需要面對的挑戰(zhàn)。本文將通過一個實際案例,詳細分析Spring事務中的刪除操作與回滾機制,并提供優(yōu)化方案。
1. 問題背景
在某個廣告流量控制系統(tǒng)中,我們需要刪除無效的媒體廣告位放量記錄。核心代碼如下:
@Service
@Transactional
public class FlowTransactionalUtil {
@Autowired
private OpmMediaFlowControlConfirmService confirmService;
public void deleteMediaFlowOnline(List<OpmMediaFlowControlEntity> list, long flowId) {
List<Long> mediaAdList = list.stream()
.map(OpmMediaFlowControlEntity::getMediaAdId)
.collect(Collectors.toList());
List<Long> deleteList = confirmService.list(QueryUtils.eq(OpmMediaFlowControlConfirmEntity::getFlowId, flowId))
.stream()
.filter(e -> !mediaAdList.contains(e.getMediaAdId()))
.map(OpmMediaFlowControlConfirmEntity::getId)
.collect(Collectors.toList());
if (!CollectionUtils.isEmpty(deleteList)) {
RollBackExcUtils.throwExc(confirmService.removeByIds(deleteList) ? 1 : 0);
}
}
}
問題現象:
當 removeByIds() 返回 false(刪除失敗或未刪除記錄)時,拋出 CustomerException 并回滾事務。
日志顯示:
com.middle.exception.CustomerException: 事務處理請求異常
2. 問題分析
2.1 事務回滾機制
Spring 默認在遇到 未捕獲的 RuntimeException 或 Error 時回滾事務。如果 CustomerException 不是 RuntimeException 的子類,需要顯式聲明@Transactional(rollbackFor = CustomerException.class)。
2.2 removeByIds 返回 false 的原因
| 原因 | 是否應回滾 | 處理建議 |
|---|---|---|
| 記錄不存在 | 否 | 記錄日志,不拋異常 |
| 并發(fā)沖突(已刪除) | 否 | 記錄日志,不拋異常 |
| 數據庫異常 | 是 | 拋異常并回滾 |
3. 優(yōu)化方案
3.1 區(qū)分業(yè)務異常與技術異常
優(yōu)化 deleteFlowConfirm 方法,避免因“記錄不存在”等合法場景觸發(fā)回滾:
private void deleteFlowConfirm(long flowId, List<OpmMediaFlowControlConfirmEntity> controlConfirms) {
List<Long> list = controlConfirms.stream()
.filter(e -> e.getFlowId().equals(flowId))
.map(OpmMediaFlowControlConfirmEntity::getId)
.collect(Collectors.toList());
if (!CollectionUtils.isEmpty(list)) {
boolean isSuccess = confirmService.removeByIds(list);
if (!isSuccess) {
// 檢查是否真的存在待刪除記錄
long actualExistCount = confirmService.count(
QueryUtils.in(OpmMediaFlowControlConfirmEntity::getId, list)
);
if (actualExistCount > 0) {
throw new CustomerException("刪除失敗,請重試或聯(lián)系管理員");
} else {
log.warn("嘗試刪除不存在的記錄: flowId={}, ids={}", flowId, list);
}
}
}
}
3.2 顯式聲明事務回滾規(guī)則
@Transactional(rollbackFor = {CustomerException.class, RuntimeException.class})
public class FlowService {
// ...
}
3.3 并發(fā)場景優(yōu)化
方案1:樂觀鎖重試
@Retryable(maxAttempts = 3, backoff = @Backoff(delay = 100))
public void deleteWithRetry(List<Long> ids) {
TransactionAssert.assertSuccess(confirmService.removeByIds(ids));
}
方案2:悲觀鎖查詢
List<OpmMediaFlowControlConfirmEntity> list = confirmService.listWithLock(
QueryUtils.eq(OpmMediaFlowControlConfirmEntity::getFlowId, flowId)
);
4. 完整優(yōu)化代碼
@Service
@Transactional(rollbackFor = CustomerException.class)
public class FlowService {
@Autowired
private OpmMediaFlowControlConfirmService confirmService;
public void deleteMediaFlowOnline(List<OpmMediaFlowControlEntity> list, long flowId) {
List<Long> mediaAdList = list.stream()
.map(OpmMediaFlowControlEntity::getMediaAdId)
.collect(Collectors.toList());
// 直接條件刪除(避免查詢-刪除競態(tài)條件)
boolean success = confirmService.deleteByFlowIdAndExcludedAdIds(flowId, mediaAdList);
TransactionAssert.assertSuccess(success);
}
}
// 事務斷言工具類
public class TransactionAssert {
public static void assertSuccess(boolean condition) {
if (!condition) {
throw new CustomerException(SupResultCode.CODE_900000, "操作失敗,請重試");
}
}
}
5. 日志與監(jiān)控建議
在關鍵位置添加日志:
try {
flowService.deleteMediaFlowOnline(list, flowId);
} catch (CustomerException e) {
log.error("刪除失敗 - flowId: {}, 錯誤: {}", flowId, e.getMessage());
throw e;
}
6. 總結
- 明確事務回滾條件:確保異常類型正確觸發(fā)回滾。
- 區(qū)分業(yè)務異常與技術異常:避免因合法場景(如記錄不存在)誤觸發(fā)回滾。
- 優(yōu)化并發(fā)操作:使用鎖機制或重試策略減少沖突。
- 增強日志記錄:便于快速定位問題。
通過以上優(yōu)化,可以顯著提升系統(tǒng)的健壯性和可維護性。
到此這篇關于Spring事務管理之如何處理刪除操作與事務回滾的文章就介紹到這了,更多相關Spring事務管理內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
SpringBoot中SpringSecurity安全框架的基本配置與使用方式
Spring Security是Spring框架的安全性解決方案,提供了身份驗證、授權、認證流程安全控制等全面安全功能,廣泛應用于Java應用程序中2026-03-03
java并發(fā)編程專題(十一)----(JUC原子類)數組類型詳解
這篇文章主要介紹了JAVA JUC原子類 數組類型詳解的相關資料,文中示例代碼非常詳細,幫助大家更好的理解和學習,感興趣的朋友可以了解下2020-07-07
spring源碼學習之bean的初始化以及循環(huán)引用
這篇文章主要給大家介紹了關于spring源碼學習之bean的初始化以及循環(huán)引用的相關資料,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2020-10-10

