DEV Community

Cover image for The Specification Pattern in Spring Data JPA: Building Composable Queries That Scale
Ed Legaspi
Ed Legaspi

Posted on Originally published at czetsuyatech.com

The Specification Pattern in Spring Data JPA: Building Composable Queries That Scale

Spring Data JPA Specifications are commonly introduced as a solution to dynamic filtering.

But they can do more than eliminate repository methods.

They allow us to express query conditions as reusable components and compose them into larger business rules.

The challenge is designing those Specifications so they remain understandable as an application grows.

Let's build a practical example using an order management system.

1. The Problem With Growing Query Logic

Imagine an order management application that needs to find:

  • Orders awaiting payment
  • High-value orders
  • Orders requiring manual review
  • Orders belonging to customers in a particular country
  • Combinations of those conditions

We could keep adding repository methods:

List<Order> findByStatus(OrderStatus status);

List<Order> findByStatusAndCurrency(
    OrderStatus status,
    String currency
);

List<Order> findByStatusAndCurrencyAndTotalAmountGreaterThanEqual(
    OrderStatus status,
    String currency,
    BigDecimal amount
);
Enter fullscreen mode Exit fullscreen mode

But these methods represent combinations of conditions rather than distinct business operations.

Instead, we can represent each condition independently.

2. Create the Domain Model

Let's start with a simplified Order entity.

@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;
}
Enter fullscreen mode Exit fullscreen mode

For the examples, assume the following statuses:

public enum OrderStatus {
    PENDING_PAYMENT,
    MANUAL_REVIEW,
    PAID,
    CANCELLED
}
Enter fullscreen mode Exit fullscreen mode

Our repository extends JpaSpecificationExecutor.

public interface OrderRepository
        extends JpaRepository<Order, Long>,
                JpaSpecificationExecutor<Order> {
}
Enter fullscreen mode Exit fullscreen mode

We can now execute composable Specifications without adding a repository method for every filter combination.

3. Create Small, Reusable Specifications

A Specification should describe 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
            );
    }
}
Enter fullscreen mode Exit fullscreen mode

Each method is independent.

None of them needs to know which other predicates will be applied.

That's what makes them composable.

4. Compose Conditions With AND

Suppose we want pending-payment orders denominated in PHP with a total amount of at least 10,000.

We can combine the Specifications using Specification.allOf().

Specification<Order> specification =
    Specification.allOf(
        OrderSpecifications.hasStatus(
            OrderStatus.PENDING_PAYMENT
        ),
        OrderSpecifications.hasCurrency("PHP"),
        OrderSpecifications.amountAtLeast(
            new BigDecimal("10000.00")
        )
    );

List<Order> orders =
    orderRepository.findAll(specification);
Enter fullscreen mode Exit fullscreen mode

Conceptually, the resulting SQL resembles:

SELECT o.*
FROM orders o
WHERE o.status = 'PENDING_PAYMENT'
  AND o.currency = 'PHP'
  AND o.total_amount >= 10000.00;
Enter fullscreen mode Exit fullscreen mode

The actual SQL depends on Hibernate and the database dialect.

Important: The threshold is meaningful only in the context of the same currency. Comparing monetary amounts across currencies without conversion can produce incorrect business results.

5. Compose Conditions With OR

Now suppose the business defines an order requiring attention as one that is either awaiting payment or under manual review.

Instead of repeating that condition throughout the application, we can create a higher-level Specification.

Add this method to OrderSpecifications:

public static Specification<Order> requiresAttention() {

    return Specification.anyOf(
        hasStatus(OrderStatus.PENDING_PAYMENT),
        hasStatus(OrderStatus.MANUAL_REVIEW)
    );
}
Enter fullscreen mode Exit fullscreen mode

Now the application can express its intent directly:

Specification<Order> specification =
    OrderSpecifications.requiresAttention();
Enter fullscreen mode Exit fullscreen mode

This is more meaningful than repeatedly constructing the same status comparisons.

If the business definition changes, the query rule can be updated in one place.

6. Logical Grouping Matters

Consider this 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
)
Enter fullscreen mode Exit fullscreen mode

We can express it as:

Specification<Order> specification =
    Specification.allOf(
        OrderSpecifications.hasCurrency("PHP"),
        OrderSpecifications.requiresAttention()
    );
Enter fullscreen mode Exit fullscreen mode

But be careful.

These expressions are not equivalent:

A AND (B OR C)
Enter fullscreen mode Exit fullscreen mode
(A AND B) OR C
Enter fullscreen mode Exit fullscreen mode

Incorrect grouping can return records that violate the intended business condition.

This is why complex Specification composition should be tested with representative data.

7. Negate Conditions With NOT

Spring Data JPA also supports negation.

For example, to exclude cancelled orders:

Specification<Order> notCancelled =
    Specification.not(
        OrderSpecifications.hasStatus(
            OrderStatus.CANCELLED
        )
    );
Enter fullscreen mode Exit fullscreen mode

You can combine negation with other conditions:

Specification<Order> specification =
    Specification.allOf(
        notCancelled,
        OrderSpecifications.hasCurrency("PHP")
    );
Enter fullscreen mode Exit fullscreen mode

Keep in mind that SQL uses three-valued logic.

For nullable database columns, negating a comparison does not necessarily include rows where the column is NULL.

In this example, status is non-nullable, so that ambiguity is avoided.

8. Query Relationships

Specifications can also filter using entity relationships.

Suppose our Customer entity contains a country field:

@Entity
@Table(name = "customer")
@Getter
@Setter
public class Customer {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @Column(nullable = false)
    private String country;
}
Enter fullscreen mode Exit fullscreen mode

We want orders belonging to customers in a particular country.

Add another Specification:

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
        );
    };
}
Enter fullscreen mode Exit fullscreen mode

Now we can combine it with existing conditions:

Specification<Order> specification =
    Specification.allOf(
        OrderSpecifications.customerInCountry("PH"),
        OrderSpecifications.requiresAttention()
    );
Enter fullscreen mode Exit fullscreen mode

The service doesn't need to know how the relationship is joined.

That logic remains inside the Specification.

Be careful with collection joins

A many-to-one join generally doesn't multiply rows for each root order.

A one-to-many join may produce multiple rows when several related records match.

This can affect result duplication, pagination, and count queries.

For existence checks against collections, an EXISTS subquery is often preferable.

Don't assume that adding DISTINCT will solve every pagination or performance problem.

9. Improve Type Safety With the JPA Static Metamodel

Our examples use string-based property names:

root.get("status")
Enter fullscreen mode Exit fullscreen mode

This works, but property names are not checked through ordinary Java member references.

A refactoring could rename an entity property while leaving a string literal unchanged.

If your project generates the JPA static metamodel, you can use:

public static Specification<Order> hasStatus(
        OrderStatus status) {

    return (root, query, cb) ->
        cb.equal(root.get(Order_.status), status);
}
Enter fullscreen mode Exit fullscreen mode

Order_ is generated by a JPA metamodel annotation processor.

This provides stronger compile-time checking of entity attributes.

It does require appropriate build configuration, so the trade-off depends on the project.

10. Execute Specifications Through a Service

Keep query composition separate from repository execution.

@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
        );
    }
}
Enter fullscreen mode Exit fullscreen mode

The responsibilities are clear:

  • The Specification defines query conditions.
  • The service chooses which conditions to apply.
  • The repository executes the query.

This separation makes the query behavior easier to test and maintain.

11. Test the Composition, Not Just the Individual Predicates

One of the most important things to test is logical grouping.

Consider a query that should return PHP orders requiring attention.

A useful test dataset includes:

Currency Status Expected
PHP PENDING_PAYMENT Included
PHP MANUAL_REVIEW Included
PHP PAID Excluded
USD MANUAL_REVIEW Excluded

The last case is especially important.

It catches a common mistake where OR conditions are grouped incorrectly.

Here's an illustrative integration test using Spring Data JPA:

@DataJpaTest
class OrderSpecificationsTest {

    @Autowired
    private OrderRepository orderRepository;

    @Test
    void shouldFindOnlyPhpOrdersRequiringAttention() {

        Specification<Order> specification =
            Specification.allOf(
                OrderSpecifications.hasCurrency("PHP"),
                OrderSpecifications.requiresAttention()
            );

        List<Order> results =
            orderRepository.findAll(specification);

        assertThat(results)
            .extracting(Order::getId)
            .containsExactlyInAnyOrder(
                pendingPhpOrderId,
                manualReviewPhpOrderId
            );
    }
}
Enter fullscreen mode Exit fullscreen mode

The example assumes the test has already persisted the four representative orders and captured their IDs.

A complete test should seed the records and assert the exact expected results.

Otherwise, an empty result set might pass weaker assertions without proving the query is correct.

For applications using PostgreSQL in production, consider PostgreSQL-backed integration tests with Testcontainers.

This helps validate behavior against the actual database engine rather than relying exclusively on an in-memory substitute.

12. Where NERV Persistence Fits

Everything we've implemented so far uses native Spring Data JPA functionality.

That's intentional.

Spring Data JPA already provides the foundation for query composition.

But across multiple applications, teams may repeatedly implement the same technical mechanics:

  • Optional filter handling
  • Comparison operators
  • Pagination conventions
  • Sorting validation
  • Common query construction

These are reasonable candidates for reusable persistence infrastructure.

NERV Persistence is built around the idea of standardizing common persistence concerns while preserving domain-specific behavior.

The intended separation is:

Application Service
        |
        v
Domain Specifications
        |
        v
Reusable Query Mechanics
        |
        v
Spring Data JPA
        |
        v
Hibernate / Database
Enter fullscreen mode Exit fullscreen mode

This is a conceptual architecture, not a representation of specific NERV Persistence classes.

The important principle is simple:

Share the mechanics of querying, not the ownership of business rules.

Domain-specific Specifications should remain close to the applications that own their meaning.

Reusable infrastructure should complement Spring Data JPA rather than hide it.

Explore the project:

NERV Persistence on GitHub

13. Production Considerations

Composable Specifications improve maintainability, but they don't automatically produce efficient SQL.

Before relying on complex Specification queries in production, consider the following.

Inspect generated SQL

A small Specification can generate a complex SQL query.

Use SQL logging and database execution plans to understand important queries.

Watch count-query performance

A Page<T> generally requires total-count information.

For complex joins or large datasets, count queries can become expensive.

Depending on your Spring Data JPA version, separate count Specifications or alternative retrieval strategies may help.

Keep fetching separate from filtering

Avoid mixing fetch joins and query mutation into reusable Specifications without understanding how they interact with pagination and count queries.

Entity graphs, projections, or dedicated query implementations may be more appropriate for complex fetching requirements.

Enforce mandatory restrictions

Tenant boundaries and authorization rules must not be removable through user-supplied search filters.

Search flexibility should never weaken data-access controls.

Don't make everything generic

A universal query builder accepting arbitrary property paths and operators can become difficult to validate, secure, and optimize.

Prefer explicit, domain-oriented Specifications when business meaning matters.

14. When Not to Use Specifications

Specifications are useful, but they're not always the right abstraction.

For a fixed lookup, a derived repository method is often clearer:

Optional<Order> findByExternalReference(
    String externalReference
);
Enter fullscreen mode Exit fullscreen mode

For specialized reporting queries involving aggregation, window functions, or database-specific features, explicit SQL may be more appropriate.

For highly optimized read models, dedicated projections or specialized query implementations may provide better control.

The goal isn't to force every query through Specifications.

It's to use composition where composition genuinely improves the design.

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 express query conditions as independent, meaningful components and combine them into larger business rules.

Used carefully, they improve readability, reuse, testability, and maintainability.

Used carelessly, they can become another abstraction layer that hides query behavior and complicates performance analysis.

The distinction comes down to design discipline:

  • Keep predicates focused.
  • Compose logical conditions explicitly.
  • Preserve domain ownership.
  • Test the resulting behavior.
  • Understand the SQL 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 practical persistence architecture for Java and Spring Boot applications.

NERV Persistence:

https://github.com/czetsuyatech/nerv-persistence

Canonical article on CzetsuyaTech:

https://www.czetsuyatech.com/2026/11/specification-pattern-spring-data-jpa-composable-queries.html

How do you organize Specifications in your Spring Boot applications? Do you keep them as simple query helpers, or compose them into higher-level business conditions?

Top comments (0)