我有一份 CRUD 作業。
讀取 -> 檢索一個物件。大多數都有值,但如果輸入了錯誤的 ID,則可能沒有回傳值。
所以我們將它包裝在一個 Optional 物件中并回傳它。
創建 -> 讓我們通過。
更新 -> 更新讀取中提到的物件。
洗掉 -> 洗掉讀取中提到的物件。
在這里,有一個 ID 指定要更新或洗掉的物件(DB 中的資料行)。
問題是我不確定資料庫中是否存在具有此 ID 的物件。
我只想在資料庫中有 ID 的值時才執行更新或洗掉。
這個時候想到的方法是執行第一個提到的Read方法,接收一個包裹在Optional中的物件,如果是通過orElseThrow()傳遞。
如果不是,我使用了引發 Throw 例外的方法。
但這似乎有些不對勁。
查詢后回傳的可選,僅檢查是否有值后銷毀。
但除此之外,我想不出一種方法來知道資料庫是否真的有價值。
寫 if == null 不是更好嗎?
下面是我實作的代碼。
請推薦一個好方法。
public Optional<CallCounselEntity> getCallCounselByUserId(UUID userId, UUID counselId) {
return return callCounselRepository.findByUserId(userId, counselId);
}
public CallCounselEntity updateCallCounsel(CallCounselEntity callCounsel) {
**getCallCounselByUserId(callCounsel.getUserId(),callCounsel.getCounselId()).orElseThrow(() -> new NoSuchElementException("No Search Data"));**
callCounselRepository.save(callCounsel));
return callCounsel;
}
uj5u.com熱心網友回復:
你是什??么意思'可選被破壞'?
你想要CallCounselEntity entity = getCallCounselByUserId(...).orElseThrow(...)。如果代碼沒有拋出,那么該方法entity現在繼續被分配一個非可選值,您可以使用該值進行更新。如果代碼拋出,那么,你的方法參考中的任何剩余代碼entity都將永遠無法到達。這就是重點。
因此,總而言之,以下是您的方案完全有效的代碼:
CallCounselEntity entity = getCallCounselByUserId(...).orElseThrow(...)
/* perform your update here */
或者,您可以使用:
getCallCounselByUserId(...).ifPresent(existingCounsel -> {
/* perform your update here */
})
或者
getCallCounselByUserId(...).ifPresentOrElse(existingCounsel -> {
/* perform your update here */
}, () -> throw new RuntimeException(...))
如果您仍然想為不存在的物體拋出例外。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/496900.html
上一篇:箭頭驗證超過10個欄位
