[英]Spring Catch JpaSystemException in @Transactional Method and Roll Back Transaction
我有一個用注釋的方法
@Transactional(isolation = Isolation.SERIALIZABLE, propagation = Propagation.REQUIRES_NEW, rollbackFor = Exception.class)
並調用幾種存儲庫方法。 現在,當一個存儲庫嘗試更改被該方法的另一個實例鎖定且未回滾的數據庫行時,spring會正確拋出
org.springframework.orm.jpa.JpaSystemException: could not execute statement [...] Caused by: java.sql.SQLException: transaction could not be serialized and rolls back the failed transaction.
現在,我想保留所有這些行為,但還要處理異常並開始重試。 這是一個代碼片段:
@Transactional(isolation = Isolation.SERIALIZABLE, propagation = Propagation.REQUIRES_NEW, rollbackFor = Exception.class)
@Lock(LockModeType.PESSIMISTIC_WRITE)
public void messageReceived(Card card) {
this.request = request;
this.numberOfAttempts = reset ? 0 : this.numberOfAttempts++;
this.reset = true;
LOGGER.info("Message received from Queue: " + card);
TransactionDebugUtils.transactionRequired("MessageReceivedController.messageReceived");
try {
[...]
repository1.createKonto(card);
repository2.doStuff(card);
} catch (JpaSystemException e) {
//This is obviously never invoked
LOGGER.error("TRANSACTION FAILED!!!");
} catch (Exception e) {
LOGGER.error("Error mapping json request to data model", message, e);
}
}
@ExceptionHandler(JpaSystemException.class)
//This is also never invoked
public void handleJpaSystemException(JpaSystemException ex) {
this.messageReceived(this.request);
this.reset = false;
}
我最近有這個問題。 由於它是方法級別的@Transactional批注,因此在方法執行完成后才進行事務提交。 使用此批注時,應考慮2個概念
執行messageReceived()方法后,將發生這兩種情況,並且在@Transactional級別上引發JPA異常,這意味着您需要從調用此方法的位置(控制器;如果從控制器調用)處理此異常。 有關@Transactional的更多信息,請參見此鏈接 。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.