Video in progress

Strong Middle 🐻 Hibernate and JPA

How do you write a search endpoint with many optional filters using Hibernate?

Instead of building JPQL by concatenating strings, I use the Criteria API or Spring Data's Specification on top of it: each filter is a separate predicate, and one that doesn't come in isn't added. In many complex cases I use a type-safe DSL (Querydsl, jOOQ) or combine it with a DTO projection.

📖 Answer

For example, an order search: status, customer name, date range, amount, all optional.

With Specification:

public final class OrderSpecs {
    public static Specification<Order> hasStatus(Status s) {
        return (root, q, cb) -> s == null ? null : cb.equal(root.get("status"), s);
    }
    public static Specification<Order> createdBetween(LocalDate from, LocalDate to) {
        return (root, q, cb) -> {
            if (from == null && to == null) return null;
            if (to == null) return cb.greaterThanOrEqualTo(root.get("createdAt"), from.atStartOfDay());
            if (from == null) return cb.lessThan(root.get("createdAt"), to.plusDays(1).atStartOfDay());
            return cb.between(root.get("createdAt"), from.atStartOfDay(), to.plusDays(1).atStartOfDay());
        };
    }
    public static Specification<Order> customerName(String name) {
        return (root, q, cb) -> name == null ? null
            : cb.like(cb.lower(root.join("customer").get("name")), "%" + name.toLowerCase() + "%");
    }
}

Page<Order> page = repo.findAll(
    Specification.where(hasStatus(f.status()))
        .and(createdBetween(f.from(), f.to()))
        .and(customerName(f.name())),
    pageable);

A predicate that returns null is ignored by Spring Data.

Problems you see in production:

  • root.get("status") uses string names; if you rename the field, the compiler doesn't complain. The JPA static metamodel (Order_.status) or Querydsl covers this.
  • If you add a join regardless of whether the filter is present, you get duplicates or an extra JOIN. Join only when the filter comes in.
  • For Page, Spring builds a separate count query; a specification with a fetch join fails in the count, so you have to check query.getResultType() and not fetch in the count.
  • like '%...%' doesn't work with a plain index. On a big table, use PostgreSQL pg_trgm or a separate search system.

For very complex reporting searches, I set the ORM aside and move to jOOQ or native SQL + a DTO.