1. 程式人生 > >springboot java.util.NoSuchElementException: No value present 異常處理

springboot java.util.NoSuchElementException: No value present 異常處理

當通過jap通過id查詢時,使用 findById(id).get(),當id不存在當,也就是資料庫沒有對應當id資料時,就回報上面當異常

後來檢視原始碼,發現:


public T get() {
     if (value == null) {
           throw new NoSuchElementException("No value present");
     }
     return value;
 }

也就是說當查不到值的時候,jap統一處理為拋異常,所以每次取之前都要判斷有沒有資料,後來發現了這個


 public boolean isPresent()
{ return value != null; }

於是程式碼就這樣寫


Optional<T> optionalT = orderDetailRepository.findById(id);
return optionalT.isPresent() ? optionalT.get(): null;