In the previous article, Dynamic Queries in Spring Data JPA Without Repository Method Explosion, we explored how optional search filters can turn a clean repository into a growing collection of derived query methods.
Spring Data JPA Specifications offer a practical solution: represent individual query conditions as predicates and compose them according to the requirements of a search operation.
But eliminating repository method explosion is only the beginning.
As applications become more complex, we encounter another challenge: how do we organize Specifications so they remain reusable, understandable, testable, and efficient?
A poorly designed Specification layer can become just as difficult to maintain as the repository methods it replaced.
In this article, we'll explore the Specification pattern beyond simple optional filters. We'll build composable business predicates, combine logical conditions, query relationships, and examine the architectural decisions that make Specifications sustainable in enterprise applications.
1. Specifications Are More Than Dynamic Filters
When developers first encounter Spring Data JPA Specifications, they often think of them as a convenient way to build dynamic WHERE clauses.
That's certainly one application, but the underlying idea is broader.
The Specification pattern, as described in domain-driven design, provides a way to represent business rules as reusable, composable conditions.
In the persistence layer, Spring Data JPA expresses these conditions through the JPA Criteria API.
@FunctionalInterface
public interface Specification<T> {
Predicate toPredicate(
Root<T> root,
CriteriaQuery<?> query,
CriteriaBuilder criteriaBuilder
);
}
This simplified representation illustrates the traditional Specification contract. Exact signatures and nullability annotations vary by Spring Data JPA version.
A Specification describes a condition without directly executing the query.
Query execution remains the responsibility of Spring Data JPA.
This separation gives us an important architectural property: the definition of a query condition is independent of the repository operation that uses it.
2. Start With a Real Domain
Consider an order management system where operators need to search orders using different business conditions.
Our simplified order entity might look like this:
@Entity
@Table(name = "orders")
@Getter
@Setter
public class Order {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Enumerated(EnumType.STRING)
@Column(nullable = false)
private OrderStatus status;
@Column(nullable = false, precision = 19, scale = 2)
private BigDecimal totalAmount;
@Column(nullable = false)
private String currency;
@Column(nullable = false)
private Instant createdAt;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "customer_id", nullable = false)
private Customer customer;
}
Suppose the business introduces the following requirements:
- Find orders awaiting payment.
- Find high-value orders.
- Find orders created within a particular period.
- Find orders belonging to customers in a particular country.
- Combine these conditions for operational dashboards.
These aren't necessarily separate repository operations. They're business conditions that can participate in different queries.
Instead of creating one large search method, let's represent these conditions independently.
3. Build Small, Meaningful Specifications
A good Specification should express one meaningful condition.
public final class OrderSpecifications {
private OrderSpecifications() {
}
public static Specification<Order> hasStatus(
OrderStatus status) {
return (root, query, cb) ->
cb.equal(root.get("status"), status);
}
public static Specification<Order> hasCurrency(
String currency) {
return (root, query, cb) ->
cb.equal(root.get("currency"), currency);
}
public static Specification<Order> amountAtLeast(
BigDecimal amount) {
return (root, query, cb) ->
cb.greaterThanOrEqualTo(
root.get("totalAmount"),
amount
);
}
}
Each method describes a condition that can be understood independently.
Notice that the method names communicate intent.
We don't need to know how the Criteria API works to understand
what amountAtLeast() means.
However, the meaning of an amount threshold must remain explicit. Comparing monetary amounts without also accounting for currency can produce misleading business results.
For example, a high-value order query might require a specific currency:
public static Specification<Order> highValueInCurrency(
BigDecimal threshold,
String currency) {
return Specification.allOf(
amountAtLeast(threshold),
hasCurrency(currency)
);
}
This is already more expressive than a generic field comparison. It encodes the business assumption that the threshold and order amounts use the same currency.
4. Compose Business Rules With AND, OR, and NOT
The real value of Specifications appears when we combine them.
Suppose we need orders that are awaiting payment and have a total amount of at least 10,000 PHP.
Specification<Order> specification =
Specification.allOf(
OrderSpecifications.hasStatus(
OrderStatus.PENDING_PAYMENT
),
OrderSpecifications.highValueInCurrency(
new BigDecimal("10000.00"),
"PHP"
)
);
Conceptually, the resulting SQL resembles:
SELECT o.*
FROM orders o
WHERE o.status = 'PENDING_PAYMENT'
AND o.total_amount >= 10000.00
AND o.currency = 'PHP';
We can also express alternatives using OR.
For example, suppose an operational dashboard should display orders awaiting payment or requiring manual review.
Specification<Order> needsAttention =
Specification.anyOf(
OrderSpecifications.hasStatus(
OrderStatus.PENDING_PAYMENT
),
OrderSpecifications.hasStatus(
OrderStatus.MANUAL_REVIEW
)
);
And we can negate a condition using Specification.not().
Specification<Order> notCancelled =
Specification.not(
OrderSpecifications.hasStatus(
OrderStatus.CANCELLED
)
);
This is where Specifications become more than a mechanism for handling nullable search parameters.
We can construct larger query rules from smaller, independently understandable business conditions.
5. Group Logical Conditions Explicitly
Once queries combine AND and OR, logical grouping becomes important.
Consider the requirement:
Find PHP orders that are either awaiting payment or under manual review.
The intended expression is:
currency = PHP
AND
(
status = PENDING_PAYMENT
OR
status = MANUAL_REVIEW
)
We can express this directly:
Specification<Order> specification =
Specification.allOf(
OrderSpecifications.hasCurrency("PHP"),
Specification.anyOf(
OrderSpecifications.hasStatus(
OrderStatus.PENDING_PAYMENT
),
OrderSpecifications.hasStatus(
OrderStatus.MANUAL_REVIEW
)
)
);
Explicit grouping matters because:
A AND (B OR C)
is not equivalent to:
(A AND B) OR C
The second expression could include manual-review orders regardless of currency.
A Specification implementation can compile successfully, return results, and still violate the intended business rule.
That's why complex predicate composition deserves behavioral tests rather than relying on code inspection alone.
6. Build Higher-Level Business Specifications
Once primitive Specifications exist, we can compose them into higher-level rules.
For example, an operations dashboard might repeatedly need orders that require attention.
public static Specification<Order> requiresAttention() {
return Specification.anyOf(
hasStatus(OrderStatus.PENDING_PAYMENT),
hasStatus(OrderStatus.MANUAL_REVIEW)
);
}
Other application components no longer need to know which statuses constitute an attention-required order.
Specification<Order> specification =
Specification.allOf(
OrderSpecifications.requiresAttention(),
OrderSpecifications.hasCurrency("PHP")
);
If the business definition changes, we update the higher-level Specification rather than searching through multiple services for duplicated status combinations.
There is an important distinction here.
Specifications are useful for expressing query-time rules, but they should not automatically become the authoritative implementation of every domain invariant.
Rules that govern whether a state transition is permitted still belong in the appropriate domain or application logic. A database query predicate alone cannot enforce every business invariant.
7. Querying Relationships With Specifications
Real applications rarely filter only scalar fields. Queries frequently involve relationships.
Suppose we need orders belonging to customers in a particular country.
Assuming Customer has a
country property, we can write:
public static Specification<Order> customerInCountry(
String country) {
return (root, query, cb) -> {
Join<Order, Customer> customer =
root.join("customer", JoinType.INNER);
return cb.equal(
customer.get("country"),
country
);
};
}
This condition can be combined with the others:
Specification<Order> specification =
Specification.allOf(
OrderSpecifications.customerInCountry("PH"),
OrderSpecifications.requiresAttention()
);
Notice that the calling service does not need to know how the relationship is joined.
The Specification encapsulates the persistence mechanics necessary to express the condition.
Be Careful With Collection Joins
Joining a many-to-one relationship generally does not multiply rows for each order, assuming the relationship is valid.
Joining a one-to-many collection is different. A root entity may appear in multiple SQL rows when several related records match.
That can affect result cardinality, pagination, and count queries.
For existence checks against collections, an
EXISTS subquery is often preferable.
Avoid treating DISTINCT as a universal fix.
It can introduce additional query costs and may not solve
every pagination or fetch-join problem.
8. Type Safety: Prefer the Static Metamodel When Appropriate
The previous examples use string-based property names:
root.get("status")
This is concise, but property names are checked at runtime rather than through ordinary Java member references.
Renaming an entity property may leave a string-based Criteria expression unchanged.
For projects using the generated JPA static metamodel, we can write:
public static Specification<Order> hasStatus(
OrderStatus status) {
return (root, query, cb) ->
cb.equal(root.get(Order_.status), status);
}
Here, Order_ is a generated metamodel class,
typically produced by the Hibernate JPA metamodel annotation
processor during compilation.
This provides stronger compile-time checking of property references, at the cost of additional build configuration.
The choice depends on the project's complexity and conventions, but type safety becomes increasingly valuable as the number of Specifications grows.
9. Keep Query Execution Separate From Query Definition
One useful architectural boundary is separating the definition of query conditions from their execution.
A repository should remain responsible for persistence access:
public interface OrderRepository
extends JpaRepository<Order, Long>,
JpaSpecificationExecutor<Order> {
}
The application service can compose the relevant business rules and execute them:
@Service
@RequiredArgsConstructor
@Transactional(readOnly = true)
public class OrderSearchService {
private final OrderRepository orderRepository;
public Page<Order> findOrdersRequiringAttention(
String currency,
Pageable pageable) {
Specification<Order> specification =
Specification.allOf(
OrderSpecifications.requiresAttention(),
OrderSpecifications.hasCurrency(currency)
);
return orderRepository.findAll(
specification,
pageable
);
}
}
The service knows which business conditions are required. The Specification knows how to express those conditions. The repository executes the resulting query.
These responsibilities are related, but they do not need to be collapsed into a single class.
10. Reusable Specifications Across Services
In a microservice architecture, similar query patterns often appear across multiple bounded contexts.
It can be tempting to create a shared library containing Specifications for every entity.
However, sharing domain-specific Specifications between services can introduce unwanted coupling.
For example, a billing service and an order management service may both have a concept of an order, but their persistence models and business responsibilities may be different.
Sharing their entity-specific query rules would tie the services to a common model that may not belong to either boundary.
A better approach is to distinguish between two categories.
Domain-Specific Specifications
These belong with the application that owns the domain:
requiresAttention()hasUnsettledBalance()eligibleForFulfillment()
Reusable Persistence Mechanics
These may be appropriate for shared infrastructure:
- Common comparison and range operations
- Optional-filter assembly
- Pagination and sorting conventions
- Validated query-field handling
- Reusable Criteria API helpers
Share the mechanics of querying, not the ownership of business meaning.
11. Where NERV Persistence Fits
This separation is closely related to the architectural goals behind NERV Persistence.
Spring Data JPA already provides the foundational abstractions needed for composable queries.
NERV Persistence builds on the broader idea that common persistence conventions and technical infrastructure should be reusable without replacing Spring Data JPA or forcing unrelated services to share domain models.
Conceptually, the responsibilities look like this:
Application Service
|
v
Domain Specifications
|
v
Reusable Query Mechanics
|
v
Spring Data JPA
|
v
Hibernate
|
v
Database
This diagram illustrates architectural responsibilities, not a claim that every layer maps to a particular NERV Persistence class.
The library should complement the framework, not hide it. Developers should still be able to use native Specifications, JPQL, Criteria API, and SQL when those are the right tools.
Explore the project: NERV Persistence on GitHub .
12. Production Considerations
Composable query design improves maintainability, but it does not automatically guarantee efficient database access.
12.1 Understand the Generated SQL
A small Specification may produce a complex SQL query, particularly when relationships, subqueries, or sorting are involved.
Use SQL logging and database execution plans to understand important queries.
For PostgreSQL, EXPLAIN (ANALYZE, BUFFERS)
can provide valuable information about actual execution,
although its execution cost and side effects should be
considered before running it against production workloads.
12.2 Keep Fetching Separate From Filtering
Specifications are best treated primarily as query predicates.
Mixing fetch joins, query ordering, and other mutations into reusable Specifications can create surprising interactions when those Specifications are composed or reused for counts.
Consider entity graphs, projections, or dedicated query implementations when fetching requirements become complex.
12.3 Be Careful With Count Queries
Paginated queries may require a count of all matching records. Complex joins and subqueries can make counts expensive.
Depending on the Spring Data JPA version, separate count Specifications can help optimize some scenarios.
When total counts are not required, consider retrieval strategies that avoid them.
12.4 Apply Mandatory Restrictions Explicitly
In multi-tenant or security-sensitive applications, user-supplied filters must not be allowed to remove mandatory visibility restrictions.
Tenant boundaries and authorization should be enforced through appropriate security and persistence controls, not merely treated as optional search filters.
12.5 Avoid Over-Generalizing the Query Layer
A generic query engine that accepts arbitrary property paths, operators, and nested expressions can become difficult to validate, secure, and optimize.
Flexibility is useful, but public query capabilities should remain intentionally constrained.
13. Testing Composable Specifications
Specifications should be tested as business query behavior, not merely as Java methods returning non-null objects.
A useful integration test verifies that the composed query returns the expected records.
@DataJpaTest
class OrderSpecificationsTest {
@Autowired
private OrderRepository orderRepository;
@Test
void shouldFindPendingOrManualReviewOrdersInPhp() {
Specification<Order> specification =
Specification.allOf(
OrderSpecifications.hasCurrency("PHP"),
OrderSpecifications.requiresAttention()
);
List<Order> results =
orderRepository.findAll(specification);
assertThat(results)
.allSatisfy(order -> {
assertThat(order.getCurrency())
.isEqualTo("PHP");
assertThat(order.getStatus())
.isIn(
OrderStatus.PENDING_PAYMENT,
OrderStatus.MANUAL_REVIEW
);
});
}
}
This illustrates the assertion structure, but a complete test must also seed representative records and verify the expected result IDs or counts.
Otherwise, an empty result could satisfy the assertions without proving that the query is correct.
Test fixtures should include both matching and nonmatching records, especially cases that distinguish:
A AND (B OR C)
from:
(A AND B) OR C
Also test relationship cardinality, date boundaries, pagination, and count behavior.
When PostgreSQL is the production database, integration tests using PostgreSQL and Testcontainers can catch differences that in-memory database tests may miss.
14. When Not to Use Specifications
Not every query benefits from a Specification abstraction.
For simple fixed lookups, derived repository methods are often more readable:
Optional<Order> findByExternalReference(
String externalReference
);
For specialized reporting, aggregation, window functions, or database-specific operations, explicit JPQL or SQL may be more appropriate.
For highly optimized read models, dedicated projections and query implementations may provide better control.
The goal is not to force every query through Specifications. It is to use composition where composition genuinely improves the design.
15. The Real Measure of a Good Specification Design
A well-designed Specification layer should make it easier to:
- Express query conditions in meaningful business terms
- Reuse predicates without duplicating logic
- Combine conditions without ambiguous grouping
- Add new requirements without modifying unrelated queries
- Test query behavior independently
- Inspect and optimize generated SQL
- Preserve domain boundaries between services
The most important benefit is not that we write fewer repository methods.
It's that we can evolve query behavior without making the persistence layer increasingly difficult to understand.
Final Thoughts
Spring Data JPA Specifications are often introduced as a solution to dynamic filtering.
But their architectural value goes further.
They allow us to represent query conditions as independent, meaningful components that can be combined into larger rules.
Used carefully, this improves readability, reuse, testability, and maintainability.
Used carelessly, Specifications can become another layer of abstraction that hides query behavior and complicates performance analysis.
The distinction comes down to design discipline: keep predicates focused, compose business rules explicitly, preserve domain ownership, and understand the SQL ultimately executed by the database.
A scalable Specification design isn't about making every query generic. It's about making query behavior composable without losing its meaning.
This is Article #3 in the NERV Persistence series, exploring reusable persistence architecture and production-oriented Spring Data JPA design.
Explore NERV Persistence: github.com/czetsuyatech/nerv-persistence
More engineering articles: CzetsuyaTech

Post a Comment