JPA Specification API
Specification pattern for composable, reusable dynamic queries with JpaSpecificationExecutor
- Define reusable query predicates as Specification classes
- Combine specifications with and(), or(), not()
- Apply specifications with pagination and sorting
CriteriaBuilder, CriteriaQuery, Root, and Predicate). It also assumes knowledge of Java Functional Interfaces and Lambda Expressions, as the Specification API is built entirely on top of them. Brief recaps are included below to keep these notes self-contained.Overview
The Specification API is a Spring Data JPA feature that provides a cleaner, more maintainable alternative to the raw Criteria API for building dynamic, type-safe queries programmatically. It is built on top of the JPA Criteria API internally, but it hides all the boilerplate object creation and solves the code duplication problem by allowing individual query conditions (Predicates) to be extracted into reusable, composable units called Specifications.
Why This Concept Exists
The raw Criteria API has two significant problems in practice:
Problem 1 Code Duplication
When writing Criteria API queries, you create Predicate objects for your WHERE conditions directly inside each repository/service method. The same predicate (e.g., "phone equals X", "name equals Y") may be needed in many different methods across many different classes. Since predicates are defined inline, the same condition logic gets copy-pasted across the codebase.
Example: If you have 50 different query methods that all filter by phone number, you would write the same cb.equal(root.get("phone"), phoneNumber) predicate 50 times — in 50 different places. If the field name changes, you must update it in 50 places.
Problem 2 Code Boilerplate
Every Criteria API query requires creating several infrastructure objects just to run a query:
1CriteriaBuilder cb = entityManager.getCriteriaBuilder();2CriteriaQuery<UserEntity> cq = cb.createQuery(UserEntity.class);3Root<UserEntity> root = cq.from(UserEntity.class);4// ... add predicates, where clause, order by, etc.5TypedQuery<UserEntity> typedQuery = entityManager.createQuery(cq);6List<UserEntity> result = typedQuery.getResultList();None of this is business logic. Your actual business concern is: from which table, with which join, and with which conditions? Everything else is infrastructure ceremony. This infrastructure code must be repeated in every method, making the codebase verbose.
How Specification API Solves These Problems
| Problem | Solution |
|---|---|
| Code Duplication | Extract each Predicate into a named static method in a dedicated UserSpecification class. Any method anywhere can call it by name — no copy-paste. |
| Code Boilerplate | Extend the repository with JpaSpecificationExecutor. This interface provides findAll(Specification), findOne(Specification), etc., and internally handles all object creation (CriteriaBuilder, CriteriaQuery, Root, TypedQuery). |
Prerequisites
Functional Interface Recap
A functional interface is an interface with exactly one abstract method. It can be implemented using a lambda expression.
1@FunctionalInterface2interface MyCondition {3 boolean check(int value);4}5
6// Lambda implementation7MyCondition isPositive = (value) -> value > 0;The `Specification<T>` Interface
Specification is a Spring Data JPA functional interface with one abstract method: toPredicate().
1public interface Specification<T> {2 Predicate toPredicate(Root<T> root, CriteriaQuery<?> query, CriteriaBuilder criteriaBuilder);3}| Parameter | Type | Description |
|---|---|---|
root | Root | Represents the entity being queried. Used to access fields: root.get("fieldName"). Also used to perform joins: root.join("relationshipField"). |
query | CriteriaQuery> | Represents the query being built. Used for ordering and grouping. |
criteriaBuilder | CriteriaBuilder | Factory for creating Predicate objects: cb.equal(...), cb.like(...), cb.and(...), etc. |
| Returns | Predicate | The WHERE condition this Specification contributes. Return null if no condition is needed (e.g., join-only specifications). |
Since Specification is a functional interface, it can be implemented as a lambda expression.
Definition
A Specification is a reusable, composable unit that encapsulates a single query condition (aPredicate) for a JPA entity. Multiple specifications can be combined usingand(),or(), andnot()to build complex queries without duplicating predicate logic or writing boilerplate infrastructure code.
Real-World Analogy
Think of building a search filter for an e-commerce site.
- Without Specification API (raw Criteria): Every search endpoint rewrites the same filter logic — "price > X", "category = Y", "brand = Z" — from scratch in every controller/service method, duplicating code everywhere.
- With Specification API: You define reusable filter "lego bricks" —
PriceGreaterThan(x),CategoryEquals(y),BrandEquals(z). Any part of your application picks up these bricks and snaps them together:PriceGreaterThan(100).and(CategoryEquals("Electronics")). The bricks are defined once, reused everywhere.
Architecture
Step-by-Step Implementation
Step 1 Extend the Repository with `JpaSpecificationExecutor`
1import org.springframework.data.jpa.repository.JpaRepository;2import org.springframework.data.jpa.repository.JpaSpecificationExecutor;3
4public interface UserDetailRepository5 extends JpaRepository<UserEntity, Long>,6 JpaSpecificationExecutor<UserEntity> {7 // No additional methods needed8 // JpaSpecificationExecutor provides: findAll, findOne, count, exists9}JpaRepository (for standard CRUD) and JpaSpecificationExecutor (for specification-based queries). Both are interfaces — Java allows multiple interface inheritance.Step 2 Create a Specification Class
Create a dedicated class (conventionally named ) with one static method per predicate. Each method returns a Specification, implemented as a lambda expression.
1import org.springframework.data.jpa.domain.Specification;2import jakarta.persistence.criteria.*;3
4public class UserSpecification {5
6 /**7 * Condition: WHERE phone = :phone8 */9 public static Specification<UserEntity> equalsPhone(String phone) {10 return (root, query, cb) -> cb.equal(root.get("phone"), phone);11 }12
13 /**14 * Condition: WHERE name = :name15 */16 public static Specification<UserEntity> equalsName(String name) {17 return (root, query, cb) -> cb.equal(root.get("name"), name);18 }19
20 /**21 * Join-only: JOIN user_address (no WHERE condition added)22 * Returns null — signals to JPA framework: no predicate, just apply the join.23 */24 public static Specification<UserEntity> joinAddress() {25 return (root, query, cb) -> {26 root.join("userAddress", JoinType.INNER); // modifies root with a join27 return null; // no WHERE condition from this specification28 };29 }30}◆ Lambda Expression Breakdown
1(root, query, cb) -> cb.equal(root.get("phone"), phone)2│ │3│ └── Implementation of Specification.toPredicate(root, query, cb)4│5└── Parameters matching toPredicate's signature:6 root → Root<UserEntity>7 query → CriteriaQuery<?>8 cb → CriteriaBuilderThe lambda is the implementation of the single abstract method toPredicate(...) of the Specification functional interface.
Step 3 Combine Specifications in the Service Layer
1import org.springframework.data.jpa.domain.Specification;2import org.springframework.stereotype.Service;3
4@Service5public class UserDetailService {6
7 private final UserDetailRepository userDetailRepository;8
9 public UserDetailService(UserDetailRepository userDetailRepository) {10 this.userDetailRepository = userDetailRepository;11 }12
13 public List<UserEntity> findUsers(String phone, String name) {14
15 Specification<UserEntity> spec = Specification16 .where(UserSpecification.joinAddress()) // JOIN user_address17 .and(UserSpecification.equalsPhone(phone)) // AND phone = ?18 .and(UserSpecification.equalsName(name)); // AND name = ?19
20 return userDetailRepository.findAll(spec);21 }22}Internal Working How JPA Resolves the Specification Tree
When you call userDetailRepository.findAll(spec), Spring Data JPA internally executes logic equivalent to this (the boilerplate that JpaSpecificationExecutor hides from you):
1// What Spring Data JPA does internally inside findAll(Specification spec):2CriteriaBuilder cb = entityManager.getCriteriaBuilder();3CriteriaQuery<UserEntity> cq = cb.createQuery(UserEntity.class);4Root<UserEntity> root = cq.from(UserEntity.class);5
6// Resolve the Specification tree into a Predicate7Predicate predicate = spec.toPredicate(root, cq, cb);8
9if (predicate != null) {10 cq.where(predicate);11}12
13TypedQuery<UserEntity> typedQuery = entityManager.createQuery(cq);14List<UserEntity> result = typedQuery.getResultList();Resolving `and()` Chains (Recursive)
When you call .and(anotherSpec), the Specification interface provides a default method that creates a composed specification:
1// Default method in Specification interface (Spring Data source)2default Specification<T> and(Specification<T> other) {3 return (root, query, cb) -> {4 Predicate left = this.toPredicate(root, query, cb); // resolve left5 Predicate right = other.toPredicate(root, query, cb); // resolve right6
7 // Handle nulls (join-only specs return null)8 if (left == null) return right;9 if (right == null) return left;10 return cb.and(left, right); // combine into AND predicate11 };12}This is recursive composition: each .and() creates a new Specification that resolves both its left and right children before combining them. The tree is resolved depth-first when toPredicate is finally called by the framework.
Full Code Example
Entity
1@Entity2@Table(name = "user_detail")3public class UserEntity {4
5 @Id6 @GeneratedValue(strategy = GenerationType.IDENTITY)7 private Long id;8
9 private String name;10 private String phone;11
12 @OneToOne(cascade = CascadeType.ALL)13 @JoinColumn(name = "address_id")14 private UserAddress userAddress;15
16 // getters, setters, constructors17}Repository
1public interface UserDetailRepository2 extends JpaRepository<UserEntity, Long>,3 JpaSpecificationExecutor<UserEntity> {4}Specification Class
1public class UserSpecification {2
3 // Condition: phone = :phone4 public static Specification<UserEntity> equalsPhone(String phone) {5 return (root, query, cb) -> cb.equal(root.get("phone"), phone);6 }7
8 // Condition: name = :name9 public static Specification<UserEntity> equalsName(String name) {10 return (root, query, cb) -> cb.equal(root.get("name"), name);11 }12
13 // Join user_address table — no WHERE condition14 public static Specification<UserEntity> joinAddress() {15 return (root, query, cb) -> {16 root.join("userAddress", JoinType.INNER);17 return null;18 };19 }20
21 // Condition: name LIKE %:keyword%22 public static Specification<UserEntity> nameLike(String keyword) {23 return (root, query, cb) -> cb.like(root.get("name"), "%" + keyword + "%");24 }25
26 // Condition: phone IS NOT NULL27 public static Specification<UserEntity> phoneIsNotNull() {28 return (root, query, cb) -> cb.isNotNull(root.get("phone"));29 }30}Service
1@Service2public class UserDetailService {3
4 private final UserDetailRepository userDetailRepository;5
6 public UserDetailService(UserDetailRepository repo) {7 this.userDetailRepository = repo;8 }9
10 // Find users where phone = ? AND name = ? AND joined with address11 public List<UserEntity> findByPhoneAndName(String phone, String name) {12 Specification<UserEntity> spec = Specification13 .where(UserSpecification.joinAddress())14 .and(UserSpecification.equalsPhone(phone))15 .and(UserSpecification.equalsName(name));16
17 return userDetailRepository.findAll(spec);18 }19
20 // Find users where name LIKE ? AND phone is not null21 public List<UserEntity> searchByName(String keyword) {22 Specification<UserEntity> spec = Specification23 .where(UserSpecification.nameLike(keyword))24 .and(UserSpecification.phoneIsNotNull());25
26 return userDetailRepository.findAll(spec);27 }28
29 // Dynamic search — conditions added only if values are provided30 public List<UserEntity> dynamicSearch(String phone, String name) {31 Specification<UserEntity> spec = Specification.where(null);32
33 if (phone != null && !phone.isBlank()) {34 spec = spec.and(UserSpecification.equalsPhone(phone));35 }36 if (name != null && !name.isBlank()) {37 spec = spec.and(UserSpecification.equalsName(name));38 }39
40 return userDetailRepository.findAll(spec);41 }42}Controller
1@RestController2@RequestMapping("/users")3public class UserController {4
5 @Autowired6 private UserDetailService userDetailService;7
8 @GetMapping("/search")9 public List<UserEntity> search(10 @RequestParam(required = false) String phone,11 @RequestParam(required = false) String name) {12 return userDetailService.dynamicSearch(phone, name);13 }14}`JpaSpecificationExecutor` Available Methods
When your repository extends JpaSpecificationExecutor, the following methods become available:
1// Find all matching records2List<T> findAll(Specification<T> spec);3
4// Find all matching records with pagination5Page<T> findAll(Specification<T> spec, Pageable pageable);6
7// Find all matching records with sorting8List<T> findAll(Specification<T> spec, Sort sort);9
10// Find one matching record (throws exception if more than one match)11Optional<T> findOne(Specification<T> spec);12
13// Count matching records14long count(Specification<T> spec);15
16// Check if any record matches17boolean exists(Specification<T> spec);CriteriaBuilder, CriteriaQuery, Root, TypedQuery) is handled internally by the framework when you call any of these methods. You provide only the Specification (the business conditions). Everything else is done for you.Specification Composition Methods
The Specification interface provides default methods for combining specifications:
| Method | Description | SQL Equivalent |
|---|---|---|
Specification.where(spec) | Starting point — wraps a specification (handles null gracefully) | WHERE ... |
.and(otherSpec) | Combines two specifications with AND | ... AND ... |
.or(otherSpec) | Combines two specifications with OR | ... OR ... |
Specification.not(spec) | Negates a specification | NOT (...) |
Example OR Condition
1Specification<UserEntity> spec = Specification2 .where(UserSpecification.equalsPhone("9999"))3 .or(UserSpecification.equalsName("Alice"));4
5// Generated WHERE: WHERE phone = '9999' OR name = 'Alice'Example NOT Condition
1Specification<UserEntity> spec = Specification2 .not(UserSpecification.equalsName("Alice"));3
4// Generated WHERE: WHERE NOT (name = 'Alice')Example Complex Combination
1Specification<UserEntity> spec = Specification2 .where(UserSpecification.equalsName("Alice"))3 .and(4 UserSpecification.equalsPhone("9999")5 .or(UserSpecification.phoneIsNotNull())6 );7
8// Generated WHERE: WHERE name = 'Alice' AND (phone = '9999' OR phone IS NOT NULL)Handling JOIN in Specifications
The Specification interface is designed primarily for WHERE conditions (predicates). JOIN operations are a secondary concern but can be handled through a workaround.
The Join Workaround
When you need to join a related table:
1public static Specification<UserEntity> joinAddress() {2 return (root, query, cb) -> {3 root.join("userAddress", JoinType.INNER); // Applies join to the root4 return null; // Return null — no WHERE condition from this spec5 };6}Why null is returned:
- Returning
nullfromtoPredicate()signals to the framework: "apply the effect of this specification (the join) but add no WHERE condition." - The framework's
and()implementation correctly handlesnullpredicates — if either side isnull, it uses only the non-null side.
cb.conjunction() is another option — it generates WHERE 1=1 (always true). However, returning null is the cleaner approach. JPA's framework code handles null predicates gracefully and does not add any condition for them.@Query. Specification API shines for dynamic WHERE clause composition.Criteria API vs Specification API Comparison
| Aspect | Raw Criteria API | Specification API |
|---|---|---|
| Boilerplate | High — must create CB, CQ, Root, TypedQuery every time | None — hidden by JpaSpecificationExecutor |
| Code duplication | High — predicates defined inline, duplicated across methods | None — predicates in reusable static methods |
| Reusability | Low — conditions are method-local | High — conditions are named, shared methods |
| Readability | Low — verbose infrastructure code mixes with business logic | High — reads like: where(condition1).and(condition2) |
| Dynamic queries | Supported but verbose | Supported and clean |
| JOIN support | Full support | Limited — join workaround needed |
| Complex projections | Supported | Not ideal |
| Composability | Manual cb.and(p1, p2, ...) | Built-in .and(), .or(), .not() |
| Setup effort | None extra | Extend JpaSpecificationExecutor + create Specification class |
Diagram Code Duplication: Before and After
Memory and Execution Flow
Key Observations
Specificationis a functional interface. It has one abstract method:toPredicate(root, query, cb). This means it can be implemented with a lambda expression — one lambda = one specification.
- Each static method in the Specification class = one reusable predicate. Define it once, use it in any number of queries across any number of classes.
JpaSpecificationExecutoreliminates all boilerplate. You never writeCriteriaBuilder,CriteriaQuery, orTypedQueryyourself. The framework creates all of these internally.
- Returning
nullfromtoPredicate()is valid and means "no condition." This is used for join-only specifications. The framework's composition methods (and(),or()) handlenullcorrectly.
- Specifications are composable.
.and(),.or(), and.not()are built-in default methods on theSpecificationinterface. They build a tree of specifications that is resolved recursively whentoPredicate()is called.
- Dynamic queries are trivially easy. Add or skip a specification based on whether a filter value is present. No if/else inside query-building code or string concatenation needed.
- Specification API is primarily for WHERE conditions. JOINs require a workaround (mutate the
root, returnnull). For complex projections or GROUP BY, Criteria API or JPQL is more appropriate.
Common Mistakes
Mistake 1 Forgetting to Extend `JpaSpecificationExecutor`
1// WRONG — findAll(Specification) method not available2public interface UserDetailRepository extends JpaRepository<UserEntity, Long> {}3
4// CORRECT5public interface UserDetailRepository6 extends JpaRepository<UserEntity, Long>,7 JpaSpecificationExecutor<UserEntity> {}Mistake 2 Defining Predicates Inline (Defeats the Purpose)
1// WRONG — predicate defined inline, not reusable2public List<UserEntity> findByPhone(String phone) {3 Specification<UserEntity> spec = (root, query, cb) ->4 cb.equal(root.get("phone"), phone); // defined here, can't reuse5 return repo.findAll(spec);6}7
8// CORRECT — predicate in dedicated Specification class9public List<UserEntity> findByPhone(String phone) {10 return repo.findAll(Specification.where(UserSpecification.equalsPhone(phone)));11}Mistake 3 Using DB Column Names Instead of Entity Field Names
1// WRONG — "phone_number" is the DB column name2(root, query, cb) -> cb.equal(root.get("phone_number"), phone)3
4// CORRECT — "phone" is the Java entity field name5(root, query, cb) -> cb.equal(root.get("phone"), phone)root.get("fieldName") expects the Java field name of the entity class, not the database column name. Using the column name (phone_number) will throw a IllegalArgumentException at runtime.Mistake 4 Not Handling `null` Values in Dynamic Queries
1// WRONG — if phone is null, cb.equal(root.get("phone"), null) produces unexpected SQL2public List<UserEntity> find(String phone) {3 return repo.findAll(Specification.where(UserSpecification.equalsPhone(phone)));4}5
6// CORRECT — guard against null before adding the specification7public List<UserEntity> find(String phone) {8 Specification<UserEntity> spec = Specification.where(null);9 if (phone != null) {10 spec = spec.and(UserSpecification.equalsPhone(phone));11 }12 return repo.findAll(spec);13}Mistake 5 Trying to Return a Meaningful Predicate from a Join-Only Spec
1// PROBLEMATIC — cb.conjunction() adds WHERE 1=1 to every query2public static Specification<UserEntity> joinAddress() {3 return (root, query, cb) -> {4 root.join("userAddress");5 return cb.conjunction(); // adds "WHERE 1=1" — unnecessary6 };7}8
9// CORRECT — return null; framework handles it gracefully10public static Specification<UserEntity> joinAddress() {11 return (root, query, cb) -> {12 root.join("userAddress");13 return null;14 };15}Best Practices
- Create one
class per entity. Keep all predicates forSpecification UserEntityinUserSpecification, all predicates forOrderEntityinOrderSpecification, etc.
- Make all specification methods
static. This allows calling them without creating an instance:UserSpecification.equalsPhone(phone).
- Name methods descriptively after the business condition they represent (
equalsPhone,nameLike,activeOnly,olderThan), not after technical details (phoneEqualsCbEqual).
- Use Specification API for dynamic queries where filter conditions change at runtime based on user input (search forms, API filter parameters). It is the cleanest solution for this use case.
- Start with
Specification.where(null)when building dynamic queries conditionally.where(null)returns a no-op specification, and.and(...)chaining on it works correctly even if no conditions are ever added.
- Combine with
PageableandSortusingfindAll(spec, pageable)for production-grade paginated, sorted, filtered endpoints.
- Reserve raw Criteria API for cases where Specification API is insufficient — complex projections, GROUP BY / HAVING, subqueries, or very complex JOIN strategies.
Interview Notes
Frequently Asked Questions
Q: What is the Specification API in Spring Data JPA?
A: Specification API is a Spring Data JPA feature that wraps the JPA Criteria API to provide reusable, composable query conditions (predicates). Each Specification represents one condition. Specifications can be combined with .and(), .or(), and .not(). The repository's JpaSpecificationExecutor executes them without any boilerplate.
Q: What are the two main problems with Criteria API that Specification API solves?
A: (1) Code duplication — predicates are defined inline and duplicated across methods/classes. Specification API extracts predicates into reusable static methods. (2) Code boilerplate — every Criteria API query requires creating CriteriaBuilder, CriteriaQuery, Root, and TypedQuery. JpaSpecificationExecutor hides all of this.
Q: What is the toPredicate() method?
A: It is the single abstract method of the Specification functional interface. It accepts Root, CriteriaQuery>, and CriteriaBuilder, and returns a Predicate. It is implemented using a lambda expression. The framework calls this method when building the final query.
Q: Why can toPredicate() return null?
A: Returning null signals that this specification contributes no WHERE condition. It is used for join-only specifications, where you want to apply a JOIN to the query but add no predicate. The framework's and() and or() methods handle null correctly — they use only the non-null predicate.
Q: How do you perform a JOIN using Specification API?
A: By calling root.join("relationshipFieldName", JoinType.INNER) inside the lambda, and returning null for the predicate. This is a workaround since Specification API is designed for predicates, not structural query changes.
Q: What does JpaSpecificationExecutor provide?
A: It provides findAll(Specification), findAll(Specification, Pageable), findAll(Specification, Sort), findOne(Specification), count(Specification), and exists(Specification) — all without any boilerplate object creation on the developer's part.
Q: How is dynamic filtering implemented cleanly with Specification API?
A: Start with Specification.where(null), then conditionally chain .and(spec) calls based on whether filter values are present. Null-safe and clean, with no string concatenation or large if/else blocks.
Mind Map
Practice Questions
Easy
- What are the two main problems with raw Criteria API that the Specification API addresses?
- What interface must a repository extend to use Specification API? What does it provide?
- What is the single abstract method in the
Specificationinterface? What are its three parameters? - Why is
Specificationconsidered a functional interface? How is it typically implemented? - What does returning
nullfromtoPredicate()mean?
Medium
- Write a
UserSpecificationclass with three static methods:equalsName(String name),phoneIsNotNull(), andnameLike(String keyword). Show how to combine all three in a service using.and(). - Write a dynamic search method in a service that accepts optional
nameandphoneparameters and adds specifications only if the values are non-null and non-blank. - How would you perform a JOIN between
UserEntityandUserAddressusing Specification API? Why must you returnnullfrom the predicate? - How do you use pagination and sorting with Specification API? Write an example.
- Compare
Specification.where(null).and(spec)vsSpecification.where(spec). What is the difference in behavior?
Hard
- Explain how
.and(otherSpec)works internally. Describe the recursive resolution of a specification tree forwhere(joinAddress).and(equalsPhone).and(equalsName). Show which predicates are resolved in what order. - You have a search form with five optional fields:
name,phone,email,city, andminAge. Design a complete solution using Specification API — theUserSpecificationclass with all five specifications, and a service method that dynamically builds the query based on which fields are filled in by the user. - Discuss the limitations of Specification API compared to raw Criteria API. In which scenarios would you choose Criteria API over Specification API despite the extra boilerplate?
Summary
- Specification API solves two raw Criteria API problems: code duplication (predicates repeated across methods) and code boilerplate (infrastructure object creation in every query).
Specificationis a functional interface with one abstract methodtoPredicate(root, query, cb). Each lambda that implements it represents one reusable query condition.
- Create a
class with oneSpecification staticmethod per predicate. Any part of the codebase calls these methods by name — no duplication.
- Extend the repository with
JpaSpecificationExecutor. This providesfindAll(spec),findOne(spec),count(spec), andexists(spec)— all boilerplate is hidden inside the framework.
- Compose specifications using
Specification.where(spec1).and(spec2).or(spec3).not(spec4). These are default methods on theSpecificationinterface that build a tree resolved recursively.
- For JOINs, mutate the
rootinside the lambda and returnnull. This is a workaround — Specification API is designed for predicates (WHERE conditions), not structural changes.
- For dynamic queries, start with
Specification.where(null)and conditionally chain.and(spec)calls.nullis handled gracefully by the framework.
- Specification API is not a replacement for JPQL or Criteria API in all cases. Complex projections, GROUP BY, HAVING, and intricate join strategies are still better served by those mechanisms.
Mastery check
How well can you recall this?
Finished this lesson?