I have a few booleans, based on these boolean I need to include a Predicate in the CriteriaQuery. However, the approach in the given example 1 does not work, as a second call on the function where() will override any previous attributes. This means that only the last Predicate will be executed.
Normally you would stack the Predicates as seen in example 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?
Example 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
query.where(cb.equal(...), cb.equal(...), cb.equal(...));
Example 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, e.g. :