Spring 数据 JPA 'AND' 查询组合

Spring Data JPA 'AND' Query combinations

我的实体 class 有四个实例变量:

参考 ID、账单 ID、客户 ID 和配置文件 ID。

都是字符串变量

我需要至少其中一项是强制性的。然后我将进行 select 查询。

如果填充了多个值,那么我想将它们组合成 'AND' 条件,然后执行 select 查询。即,如果填写了账单 ID 和客户 ID,则 select * from ... where billingID ="..." AND customerID = "..."

同样如果填三个值那么三个变量之间应该有'AND'条件。

我有一个存储库 class,它扩展了 crud 存储库。

除了编写多个查询方法(即 findByBillingID、findByBillingIDAndCustomerID 等)之外,是否有更简单的方法来执行此操作...

是的。您可以 Criteria and Restrictions 向查询添加不同的条件。它在功能上与使用 HQL 查询字符串相同,但它使用 API 代替。因此,在您的情况下,您的代码可能如下所示:

String ref, billing, customer, profile;
//get the values for those here
Criteria crit = session.createCriteria(MyEntity.class);
if(ref != null){
    crit.addRestriction(Restrictions.equals("ref", ref));
}
if(billing != null){
    crit.addRestriction(Restrictions.equals("billing", billing));
}
//...etc
return crit.list();//returns your results