我有包含布爾自定義查詢的存盤庫的 Java springBoot 專案。但系統運行到空指標例外除了回傳“假”。這是查詢:
@Query(value = "select * from customers_vs_coupons where customer_id =? and coupon_id = ?", nativeQuery = true)
Boolean existsPurchesedCoupon(int customerId, int couponId);
我呼叫了這個方法:
if (customerRepository.customerPurchesedCoupon(customerId, coupon.getId())) {
throw new PurchaseCouponException("can buy only once.");
這是錯誤:
[Request processing failed; nested exception is java.lang.NullPointerException: Cannot invoke "java.lang.Boolean.booleanValue()" because the return value of "com.chana.repositories.CustomerRepository.customerPurchesedCoupon(int, int)" is null] with root cause ```
uj5u.com熱心網友回復:
您的查詢
select * from customers_vs_coupons where customer_id =? and coupon_id = ?
旨在回傳映射到表 customer_vs_coupons 的任何物體(從現在開始稱為 CustomersVsCoupons),而不是布林值。
如果您想在特定客戶的優惠券已經受到影響時拋出例外,您應該將方法的簽名轉換為:
- 回傳一個 CustomersVsCoupons,如果您的查詢沒有回傳 null,則拋出例外
- 回傳一個 Optional<CustomersVsCoupons>,如果您的查詢確實回傳了一個非空 Optional,則拋出例外
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/454150.html
