Skip to content
Advertisement

Implement Search specification for pagination

I implemented this Page request:

JavaScript

The question is how to implement search functionality for this Page request? I would like to send params like type and dateAdded into GET params and return filtered result?

Advertisement

Answer

There are two ways to achieve this:

  1. Examples. Simple but can only be used for simple searches
JavaScript

To be able to search by example, you need make sure your ProductRepository interface extends from QueryByExampleExecutor:

JavaScript

In your service method, you can simply pass the example object:

JavaScript

See https://docs.spring.io/spring-data/jpa/docs/current/reference/html/#query-by-example.matchers for more information

  1. Using JPA Specification. This is useful in case the search parameters are more complex (e.g. when you need to join other entities)
JavaScript

The ProductSearchParams class could look like this:

JavaScript

To use the search params, we need a Specification. To use this, you need make sure your ProductRepository interface extends from JpaSpecificationExecutor:

JavaScript

Since the Specification interface has only one method, we can use a lambda in our service:

JavaScript

Using Specification is more powerful, but also a bit more work. See https://docs.spring.io/spring-data/jpa/docs/current/reference/html/#specifications for information on using Specifications. Using Specifications also allows you to write really elegant expressions, e.g. customerRepository.findAll( isLongTermCustomer().or(hasSalesOfMoreThan(amount)));

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement