I have Java springBoot project With repository that included boolean custom query. but the system run to null pointer exception apart from return "false". this is the query:
@Query(value = "select * from customers_vs_coupons where customer_id =? and coupon_id = ?", nativeQuery = true)
Boolean existsPurchesedCoupon(int customerId, int couponId);
I called the method:
if (customerRepository.customerPurchesedCoupon(customerId, coupon.getId())) {
throw new PurchaseCouponException("can buy only once.");
and this is the error:
[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 ```
CodePudding user response:
Your query
select * from customers_vs_coupons where customer_id =? and coupon_id = ?
is designed to return whatever entity (called CustomersVsCoupons from now on) is mapped to the table customer_vs_coupons, not a Boolean.
If you want to throw an exception whenever a specific customer already has a coupon affected, you should transform the signature of your method to either:
- Return a CustomersVsCoupons, and throw an exception if your query did not return null
- Return an Optional<CustomersVsCoupons>, and throw an exception if your query did return a non empty Optional