Scrivio Interview library
CodingFoundations6 min read · updated 12 November 2026

Write Spring Data JPA Specifications for 'status equals' and 'created after' and combine them in a repository call.

Make the repository extend both JpaRepository<Order, Long> and JpaSpecificationExecutor<Order>, then write each filter as a static method returning a Specification, for example hasStatus(Status s) returning (root, q, cb) -> cb.equal(root.get("status"), s) and createdAfter(Instant t) returning (root, q, cb) -> cb.greaterThan(root.get("createdAt"), t). Combine them with and() and pass the result to the repository: repository.findAll(hasStatus(PAID).and(createdAfter(t)), pageable). The Specification API has changed across Spring Data versions, for example in how a null or empty specification is created, so check your version.

Why this question is asked

Search screens with optional filters are where derived query methods stop working: with five optional filters there are thirty-two combinations, and nobody wants thirty-two repository methods. Specifications solve this by turning each filter into a small object we can combine at runtime. Interviewers ask for the code to see whether we know the pieces, the executor interface, the lambda's three arguments and how the combination becomes SQL, and whether we handle optional filters cleanly. In this answer, we will recap what a Specification is, set up the repository, write the two filters, combine them in a call with paging, handle optional filters, and note the version differences and the type-safe metamodel.

1A Quick Recap: What a Specification Is

A Specification<T> is a functional interface from Spring Data JPA with one method, toPredicate(Root<T> root, CriteriaQuery<?> query, CriteriaBuilder cb). It builds one condition, a Predicate, using the JPA Criteria API, the standard Java API for building queries as objects instead of strings.

The three arguments are the pieces of that API. root represents the entity in the from clause, and root.get("status") is a path to its status field. query is the query being built, useful for distinct or subqueries. cb, the CriteriaBuilder, creates conditions such as equal, greaterThan and like. Because Specification has default methods and(), or() and not(), small specifications combine into bigger ones.

2Setting Up the Repository

The repository gains Specification support by extending JpaSpecificationExecutor<T> next to JpaRepository. That interface adds findAll(Specification), findAll(Specification, Pageable), findOne, count, exists and, in recent versions, delete and a fluent findBy.

Java
@Entity @Table(name = "orders")
class Order {
@Id @GeneratedValue Long id;
@Enumerated(EnumType.STRING) Status status;
Instant createdAt;
BigDecimal total;
}
interface OrderRepository extends JpaRepository<Order, Long>, JpaSpecificationExecutor<Order> { }

3Writing the Two Specifications

We keep the filters as static methods in a small final class, so each has a clear name and can be reused across services.

Java
final class OrderSpecs {
private OrderSpecs() { }
static Specification<Order> hasStatus(Status s) {
return (root, q, cb) -> cb.equal(root.get("status"), s);
}
static Specification<Order> createdAfter(Instant t) {
return (root, q, cb) -> cb.greaterThan(root.get("createdAt"), t);
}
}

Notice that each method returns a lambda, not a predicate. The lambda runs later, when Spring Data builds the query, because only then do the root and the builder exist. root.get("createdAt") uses the Java field name, not the column name, and cb.greaterThan works here because Instant is Comparable.

4Combining Them in a Repository Call

Now we combine the two with and() and pass the result, with a Pageable, to the repository.

Java
import static com.example.orders.OrderSpecs.*;
Instant weekAgo = Instant.now().minus(7, ChronoUnit.DAYS);
Pageable pageable = PageRequest.of(0, 20, Sort.by("createdAt").descending());
Page<Order> page = orderRepository.findAll(hasStatus(Status.PAID).and(createdAfter(weekAgo)), pageable);
// select o.id, o.created_at, o.status, o.total from orders o
// where o.status = ? and o.created_at > ?
// order by o.created_at desc fetch first ? rows only
// select count(o.id) from orders o where o.status = ? and o.created_at > ?
// page.getTotalElements() -> 312
Step throughFrom Specification to SQL
ServiceRepositorySpecificationHibernate
findAll(hasStatus.and(createdAfter), pageable)
create CriteriaQuery and Root<Order>
toPredicate(root, query, cb)
status = ? and createdAt > ?
run query with where, order by, limit
run count query with the same where
Page<Order>

7 messages in order. Play them, or step through them one at a time.

The lambdas run only when the repository builds the query.

Because the result is a Page, Spring Data runs the content query and a count query, both with the same where clause. If we only need to know whether there is a next page, findBy with a fluent query or a Slice-returning approach avoids the count.

5Handling Optional Filters

The real use of Specifications is a search where each filter may be absent. The clean way is to add a specification only when its value is present. Recent Spring Data releases added Specification.unrestricted(), a specification that matches everything, as the recommended starting point; older versions used Specification.where(null), which newer versions deprecate. Exactly which release made the change matters here, so check your version and use the form it supports.

Java
Specification<Order> search(Status status, Instant after) {
Specification<Order> spec = Specification.unrestricted(); // recent versions; check yours
// older versions: Specification<Order> spec = Specification.where(null);
if (status != null) spec = spec.and(hasStatus(status));
if (after != null) spec = spec.and(createdAfter(after));
return spec;
}
orderRepository.findAll(search(Status.PAID, null), pageable);
// where o.status = ?
orderRepository.findAll(search(null, null), pageable);
// no where clause: all orders, paged

Notice that the empty search still pages, so it never loads the whole table. A different style returns null from toPredicate when the value is null, which the Criteria code treats as no condition, but explicit ifs are easier to read.

6Making It Type-Safe With the Metamodel

The string "createdAt" is a weakness: if someone renames the field, the code compiles and fails at runtime. The JPA static metamodel fixes that. Hibernate's annotation processor generates a class Order_ with a typed attribute for every field, so root.get(Order_.createdAt) is checked by the compiler and knows the attribute's type.

Java
// generated by the hibernate-processor (jpamodelgen in older versions) at compile time
static Specification<Order> createdAfter(Instant t) {
return (root, q, cb) -> cb.greaterThan(root.get(Order_.createdAt), t);
}
// renaming createdAt in Order now breaks compilation here

The processor's artifact name changed between Hibernate versions, from hibernate-jpamodelgen to hibernate-processor, so check your version when adding it to the build.

7Follow-up questions

How do you add a join in a Specification?

Use root.join("customer") and build the condition on the joined path, for example cb.equal(root.join("customer").get("country"), c). For to-many joins, set query.distinct(true) or use an exists subquery, because a join can return the same order several times.

Can Specifications return projections?

Recent versions of JpaSpecificationExecutor have findBy(spec, q -> q.as(OrderView.class).page(pageable)), a fluent query that can project to an interface or DTO. Check your version for its exact capabilities, since support for projections there has improved over time.

Where should Specifications live?

Next to the module's repository, in a final class with static factory methods named after the business rule, such as OrderSpecs.overdue(). That keeps each rule in one place and makes the call site read like a sentence.

8Conclusion

In this answer, we saw that a Specification is a lambda that builds a Criteria API predicate from a root, a query and a builder. The repository extends JpaSpecificationExecutor, filters such as hasStatus and createdAfter are static factory methods, and and() combines them into a call like findAll(hasStatus(PAID).and(createdAfter(t)), pageable). Optional filters are added one by one starting from an unrestricted specification, how that empty specification is created depends on the Spring Data version, and the static metamodel removes the string field names.

What to say in the interviewAbout 80 seconds aloud

Open with

First, the repository extends JpaSpecificationExecutor<Order> in addition to JpaRepository<Order, Long>. That adds findAll, count and exists methods that take a Specification. A Specification is a functional interface whose method gets the root, which is the entity in the from clause, the CriteriaQuery and the CriteriaBuilder, and returns a predicate.

Then, if they want more

So I write the filters as static factory methods in an OrderSpecs class. hasStatus(Status s) returns a lambda that does cb.equal on root.get("status") and s. createdAfter(Instant t) returns a lambda that does cb.greaterThan on root.get("createdAt") and t.

Then the call is orderRepository.findAll(hasStatus(PAID).and(createdAfter(t)), pageable), which produces where status = ? and created_at > ? with the order by and limit from the Pageable, plus a count query because it returns a Page.

For a search with optional filters, I start from an empty specification and add each filter only when its value is present, so one method covers every combination.

One thing to watch is that the API has changed across versions: Specification.where(null) was the old way to start empty, and recent versions added Specification.unrestricted() and deprecated the older form, so I check which version we are on.

I would also use the JPA static metamodel, Order_.createdAt instead of the string, so a renamed field breaks compilation rather than failing at runtime.

About this answer

Last updated
12 November 2026
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "Write Spring Data JPA Specifications for 'status equals' and 'created after' and combine...": https://scrivio-interview-library.netlify.app/databases/spring-data-jpa/5c7d49aae5/