Video in progress

When do you use the Specification pattern to express complex search and filtering rules in domain language, and what are its limits?

When the same business condition is used both in an in-memory check and in a DB query, or when conditions are combined dynamically, Specification is useful. But it tries to join two worlds (Java predicates and SQL), and in complex queries the abstraction leaks.

📖 Answer

For example, "overdue loan": past its due date, with a remaining balance, not restructured. This condition is used:

  • when checking a loan object (loan.isOverdue()),
  • when fetching a list from the DB,
  • in a report. If it's written three different ways in three places, one day they'll diverge.

In Spring Data JPA, Specification exists for exactly this:

public final class LoanSpecs {
    public static Specification<Loan> overdue(LocalDate today) {
        return (root, q, cb) -> cb.and(
            cb.lessThan(root.get("dueDate"), today),
            cb.greaterThan(root.get("remaining"), BigDecimal.ZERO),
            cb.isFalse(root.get("restructured")));
    }
    public static Specification<Loan> inBranch(BranchId b) {
        return (root, q, cb) -> cb.equal(root.get("branchId"), b.value());
    }
}

repo.findAll(overdue(today).and(inBranch(branch)), pageable);

The benefit: conditions get business names, and dynamic filters (optional filters coming from the UI) are assembled without a chain of ifs.

Limits:

  • Keeping two implementations in sync. The in-memory isOverdue() and the SQL Specification are still written in two places. Check them with one test suite: on the same data, both must give the same result.
  • Complex queries. Aggregates, window functions, CTEs: code in the Criteria API that you can't read. In such places plain native SQL or jOOQ is more honest.
  • Performance isn't visible. You only see what SQL comes out of a combination of specs in the log, and checking indexes gets harder.
  • String field names break on refactoring; with the JPA static metamodel (Loan_.dueDate) the compiler checks them.

My rule: Specification is for simple conditions with a business name that get combined often. For reports and analytical queries, use a separate read side.