我目前有一個用例,如果我的用戶手動插入要讀取的資料檔案到資料庫中,我需要檢查資料是否存在于資料庫中。如果是這樣,我想洗掉它,然后處理并保存新檔案。這樣做的問題是我的方法被標記為@Transactional,因此即使運行了洗掉方法,它們也不會在呼叫 save 方法之前提交,這違反了導致回滾的唯一約束。
我已經嘗試了每個級別的傳播,還嘗試將它們分成兩個單獨的事務,我的控制器一個接一個地呼叫它們并且它們不互相呼叫。
錯誤:org.springframework.transaction.UnexpectedRollbackException: Transaction silently rolled back because it has been marked as rollback-only
代碼:
@Transactional
public void saveAllPositionData(InputStream is) throws IOException {
log.info("Parsing position data...");
ParsingResult parsingResult = positionParser.parse(is);
if (!parsingResult.getPositions().isEmpty()) {
LocalDate businessDate = parsingResult.getPositions().get(0).getBusinessDate();
overwriteData(businessDate);
}
try {
positionRepo.saveAll(bpsParsingResult.getPositions()); // UNIQUE CONSTRAINT FAILS HERE CAUSING ROLLBACK
priceRepo.saveAll(parsingResult.getPrices());
for (PositionTable position : parsingResult.getPositions()) {
if (position.getNumberOfMemos() > 0) memoRepo.saveAll(position.getCorrespondingMemos());
}
} catch (Exception e) {
log.warn("Invalid data returned from BPS parsing job: {}", e.getMessage());
}
}
@Transactional(propagation = Propagation.NESTED) // Tried Propagation.* and no Annotation
public void overwriteData(LocalDate businessDate) {
if (memoRepo.countByBusinessDate(businessDate) > 0) {
log.warn(
"Memo record(s) found by {} business date. Existing data will be overridden.",
businessDate);
memoRepo.deleteByBusinessDate(businessDate);
}
if (positionRepo.countByBusinessDate(businessDate) > 0) {
log.warn(
"Position record(s) found by {} business date. Existing data will be overridden.",
businessDate);
positionRepo.deleteByBusinessDate(businessDate);
}
if (priceRepo.countByBusinessDate(businessDate) > 0) {
log.warn(
"Price record(s) found by {} business date. Existing data will be overridden.",
businessDate);
priceRepo.deleteByBusinessDate(businessDate);
}
}
uj5u.com熱心網友回復:
UnexpectedRollbackException通常發生在內部@Transactional方法拋出例外但外部@Transactional方法捕獲此例外但不重新拋出它時。(有關更多詳細資訊,請參閱
Spring 為您創建了事務性 UserService 代理,但是一旦您進入 UserService 類并呼叫其他內部方法,就不再涉及代理了。這意味著,您沒有新的交易。
解決此問題的一種方法是自我注入或此處
另一個是將這兩種方法保留在不同的類中。
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/515685.html
