假设我有实体(为简洁起见,省略了getters/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的给定客户的所有优惠券。我已经按照docs中的描述在CouponRepository中定义了一个方法,但失败了
@Repository
public interface CouponRepository extends CrudRepository<Coupon, Long> {
Collection<Coupon> findByCustomerAndUsedOnIsNull(Customer);
}但这会导致编译器错误Syntax error, insert "... VariableDeclaratorId" to complete FormalParameterList。
发布于 2015-04-05 01:50:20
我的错,正确的定义是
@Repository
public interface CouponRepository extends CrudRepository<Coupon, Long> {
Collection<Coupon> findByCustomerAndUsedOnIsNull(Customer customer);
}我只是遗漏了参数名:-(
发布于 2018-09-24 15:01:21
您可以使用IsNull来检查JPA查询中的空列。
例如,对于任何columnA查询,您都可以编写类似的查询
findByColumnAIsNull在这种情况下,您可以编写如下查询
@Repository
public interface CouponRepository extends CrudRepository<Coupon, Long> {
Collection<Coupon> findByCustomerAndUsedOnIsNull(Customer customer);
List<Coupon> findByUsedOnIsNull();
}您还可以检查此查询的结果

参考这篇Spring Data JPA查询创建,这将帮助您理解和创建不同类型的JPA查询变体。
https://docs.spring.io/spring-data/jpa/docs/current/reference/html/#jpa.query-methods.query-creation
发布于 2015-04-05 01:33:26
试着把你的方法改成这样(假设Customer.id是一个长整型的):
Collection<Coupon> findByCustomer_IdAndUsedOnIsNull(Long customerId);
然后像这样使用:
repo.findByCustomer_IdAndUsedOnIsNull(customer.getId());
https://stackoverflow.com/questions/29448282
复制相似问题