Spring数据查询,其中列为null

lrk*_*kwz 24 spring spring-data spring-data-jpa

假设我有实体(为了简洁省略了getter/setter和各种细节):

@Entity
class Customer{
    ...
    @OneToMany(cascade = CascadeType.ALL, mappedBy = "customer")
    Collection<Coupon> coupons;
}

@Entity
class Coupon{
    ...
    @Temporal(value = TemporalType.TIMESTAMP)
    private Date usedOn;

    @ManyToOne(fetch = FetchType.LAZY)
    @NotNull
    Customer customer;
}
Run Code Online (Sandbox Code Playgroud)

我希望检索具有null usedOn的给定客户的所有优惠券.我没有成功定义CouponRepository中的方法,如文档中所述

@Repository
public interface CouponRepository extends CrudRepository<Coupon, Long> {
     Collection<Coupon> findByCustomerAndUsedOnIsNull(Customer);
}
Run Code Online (Sandbox Code Playgroud)

但这会导致编译错误Syntax error, insert "... VariableDeclaratorId" to complete FormalParameterList.

lrk*_*kwz 18

我的错,正确的定义是

@Repository
public interface CouponRepository extends CrudRepository<Coupon, Long> {
     Collection<Coupon> findByCustomerAndUsedOnIsNull(Customer customer);
}
Run Code Online (Sandbox Code Playgroud)

我只是错过了参数名称:-(

  • 哇哈哈,至少这篇文章帮助我找到了如何使用“ IsNull” (4认同)

Xor*_*rty 13

尝试将您的方法更改为此(假设Customer.id很长):

Collection<Coupon> findByCustomer_IdAndUsedOnIsNull(Long customerId);

然后使用这样:

repo.findByCustomer_IdAndUsedOnIsNull(customer.getId());


Nik*_*had 8

您可以使用IsNull来检查JPA查询中的空列。

例如,对于任何columnA,您都可以编写查询之类的查询,例如

findByColumnAIsNull
Run Code Online (Sandbox Code Playgroud)

在这种情况下,您可以编写如下查询

@Repository
public interface CouponRepository extends CrudRepository<Coupon, Long> {
 Collection<Coupon> findByCustomerAndUsedOnIsNull(Customer customer);
 List<Coupon> findByUsedOnIsNull();
}
Run Code Online (Sandbox Code Playgroud)

您也可以检查此查询的方式 在此处输入图片说明 请参考此Spring Data JPA查询创建,这将帮助您了解和创建不同类型的JPA查询变体。

https://docs.spring.io/spring-data/jpa/docs/current/reference/html/#jpa.query-methods.query-creation