79638089

Date: 2025-05-25 21:29:30
Score: 0.5
Natty:
Report link

or() is supported by CriteriaBuilder, see the details there: https://www.baeldung.com/jpa-and-or-criteria-predicates

public List<User> searchUsers(String name, Integer age, Boolean active,
      boolean matchAny) {
CriteriaBuilder cb = entityManager.getCriteriaBuilder();
CriteriaQuery<User> query = cb.createQuery(User.class);
Root<User> root = query.from(User.class);

List<Predicate> predicates = new ArrayList<>();

if (name != null && !name.isEmpty()) {
    predicates.add(cb.like(cb.lower(root.get("name")), "%" + name.toLowerCase() + "%"));
}

if (age != null) {
    predicates.add(cb.equal(root.get("age"), age));
}

if (active != null) {
    predicates.add(cb.equal(root.get("active"), active));
}

if (!predicates.isEmpty()) {
    Predicate finalPredicate = matchAny
        ? cb.or(predicates.toArray(new Predicate[0]))
        : cb.and(predicates.toArray(new Predicate[0]));
    query.where(finalPredicate);
}

return entityManager.createQuery(query).getResultList();

}

Reasons:
  • Probably link only (1):
  • Long answer (-0.5):
  • Has code block (-0.5):
  • Low reputation (0.5):
Posted by: Maria