Spring Data查询空列

58
假设我有一些实体(为了简洁起见省略了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;
}

我希望检索出所有具有空usedOn属性的给定客户的优惠券。 我已经按照文档中描述的方式,在CouponRepository中定义了一个方法,但没有成功。

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

但这会导致编译器错误语法错误,插入“... VariableDeclaratorId”以完成FormalParameterList

3个回答

52

我的错,正确的定义是

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

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


19
哇,哈哈。至少这篇帖子帮助我找到了如何使用“IsNull”。 - GabrielBB

33
您可以使用IsNull在JPA查询中检查空列。例如,对于任何columnA,您可以编写类似以下的查询:query like
findByColumnAIsNull

在这种情况下,您可以编写像以下这样的查询:

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

同时,您还可以检查这些查询的方式,如下图所示:

enter image description here

请参考Spring Data JPA Query创建,这将帮助您了解和创建不同类型的JPA查询变体。

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


尼昆吉·安德哈德,虽然这个链接可能回答了问题,但最好在此处包含答案的基本部分并提供参考链接。[仅仅是一个链接的答案可能会被删除。] (//stackoverflow.com/help/deleted-answers) - 4b0
@Shree,我在答案中更新了完整的描述,您认为现在大家都能理解遇到这个问题时该怎么做了吗? - Nikunj Undhad

14
尝试更改您的方法为以下内容(假设Customer.id是一个长整型): Collection<Coupon> findByCustomer_IdAndUsedOnIsNull(Long customerId); 然后按照以下方式使用: repo.findByCustomer_IdAndUsedOnIsNull(customer.getId());

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接