简体   繁体   English

JPA 存储库 Boolean 查询 - 返回 null 指针异常

[英]JPA repository Boolean Query - return null pointer exception

I have Java springBoot project With repository that included boolean custom query.我有 Java springBoot 项目,其存储库包含 boolean 自定义查询。 but the system run to null pointer exception apart from return "false".但系统运行到 null 指针异常除了返回“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   ```

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.旨在返回映射到表 customer_vs_coupons 的任何实体(从现在开始称为 CustomersVsCoupons),而不是 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返回 CustomersVsCoupons,如果您的查询未返回 null,则抛出异常
  • Return an Optional<CustomersVsCoupons>, and throw an exception if your query did return a non empty Optional返回一个 Optional<CustomersVsCoupons>,如果您的查询确实返回了一个非空 Optional,则抛出异常

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM