You can use either CriteriaBilder#disjunction()
operator in order to build a Predicate to be dynamically modified:
Integer aValue, xValue, yValue;
Predicate p = cb.disjunction();
if (aValue != null) {
p = cb.or(p, cb.equal(foo.get("a"), aValue));
}
...
if (xValue != null && yValue != null) {
p = cb.or(p, cb.and(cb.equal(foo.get("x"), xValue), cb.equal(foo.get("y"), yValue)));
}
Or use an array of predicates:
List<Predicate> predicateArray = new ArrayList<> ();
if (aValue != null) {
predicateArray.add(cb.equal(foo.get("a"), aValue));
}
...
if (xValue != null && yValue != null) {
predicateArray.add(cb.and(cb.equal(foo.get("x"), xValue), cb.equal(foo.get("y"), yValue)));
}
Predicate p = cb.or(predicateArray.toArray(new Predicate[] {})));