[英]Java JPA: conditional predicates, how to leave out one depending on boolean
I have a few booleans, based on these boolean I need to include a Predicate
in the CriteriaQuery
. 我有一些布尔值,基于这些布尔值,我需要在CriteriaQuery
包含一个Predicate
。 However, the approach in the given example 1 does not work, as a second call on the function where()
will override any previous attributes. 但是,给定示例1中的方法不起作用,因为对函数的第二次调用where()
将覆盖任何先前的属性。 This means that only the last Predicate
will be executed. 这意味着只会执行最后一个Predicate
。
Normally you would stack the Predicates
as seen in example 2. 通常,您将堆叠Predicates
如示例2中所示。
However, due to the conditions given by the booleans this is not possible. 但是,由于布尔条件给出的条件,这是不可能的。 I am trying to prevent a situation as seen in example 3. Any suggestions? 我试图阻止如示例3中所示的情况。任何建议?
Example 1 例1
function(boolean a, boolean b, boolean c) {
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<Product> query = cb.createQuery(Product.class);
Root product = query.from(Product.class);
query.select(product);
if(a) {
query.where(cb.equal(...));
}
if(b) {
query.where(cb.equal(...));
}
if(c) {
query.where(cb.equal(...));
}
return em.createQuery(query).getResultList();
}
Example 2 例2
query.where(cb.equal(...), cb.equal(...), cb.equal(...));
Example 3 例3
if(a && b && c) { query.where(cb.equal(...), cb.equal(...), cb.equal(...)); }
if(a && b && !c) { query.where(cb.equal(...), cb.equal(...)); }
if(a && !b && c) { query.where(cb.equal(...), cb.equal(...)); }
if(a && !b && !c) { query.where(cb.equal(...)); }
(...)
You could collect them in a list and then set the where clause at the end, eg : 您可以在列表中收集它们,然后在结尾处设置where子句,例如:
private final List<Predicate> predicates = new ArrayList<Predicate>(3);
...
if(a) {
predicates.add(cb.equal(...));
}
if(b) {
predicates.add(cb.equal(...));
}
if(c) {
predicates.add(cb.equal(...));
}
...
query.where(predicates.toArray(new Predicate[predicates.size()]));
...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.