Sobes.tech
Senior

How to construct dynamic queries when filter conditions are unknown in advance (e.g., 10 optional fields)?

sobes.tech AI

Answer from AI

To build dynamic queries with multiple optional filters in Java, the "Builder" pattern or specialized query-building APIs such as JPA's Criteria API or QueryDSL are often used.

The main idea is to add conditions to the query only if the corresponding field is present and not empty. This avoids bulky nested if statements and string concatenation.

Example using JPA Criteria API:

CriteriaBuilder cb = entityManager.getCriteriaBuilder();
CriteriaQuery<Entity> cq = cb.createQuery(Entity.class);
Root<Entity> root = cq.from(Entity.class);
List<Predicate> predicates = new ArrayList<>();

if (filter.getField1() != null) {
    predicates.add(cb.equal(root.get("field1"), filter.getField1()));
}
if (filter.getField2() != null) {
    predicates.add(cb.like(root.get("field2"), "%" + filter.getField2() + "%"));
}
// ... add other conditions similarly

cq.where(cb.and(predicates.toArray(new Predicate[0])));
List<Entity> results = entityManager.createQuery(cq).getResultList();

This approach is flexible, safe (no risk of SQL injection), and easily extendable when adding new filters.