我想要做的是,如果客戶存在則更新客戶,但如果沒有客戶則拋出例外。但我找不到正確的流函式來做到這一點。我怎樣才能做到這一點?
public Customer update(Customer customer) throws Exception {
Optional<Customer> customerToUpdate = customerRepository.findById(customer.getId());
customerToUpdate.ifPresentOrElse(value -> return customerRepository.save(customer),
throw new Exception("customer not found"));
}
我無法回傳來自 save 函式的值,因為它說它是 void 方法并且不期望回傳值。
uj5u.com熱心網友回復:
正如 Guillaume F. 在評論中已經說過的,你可以在orElseThrow這里使用:
Customer customer = customerRepository.findById(customer.getId())
.orElseThrow(() -> new Exception("customer not found"));
return customerRepository.save(customer);
順便說一句,避免拋出Exception,因為該例外太廣泛了。使用更具體的型別,例如NotFoundException.
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/458708.html
上一篇:如何從SpringBoot的ExceptionHandler中的請求中獲取正文資料?
下一篇:系統未例外退出
