This tutorial is to show how specifications are used with spring data jpa.
We have this entity

And what we want to do on front end side is to filter the People based on the values of fields.
e.g All people with brown eyecolor and age is older than 25 and who has profile picture.

Since this query parameters can be changed dynamically, we need to come up with a flexible query generation solution which is JPA’s query builders Specification approach.

Specification provides a flexible configurable query generation logic for us. An example Specification is as follows

We are creating specification based on hasPicture condition which would lead query to check if Person picture is null or not.

The Specification implements the method with parameters Root root, CriteriaQuery<?> query, CriteriaBuilder cb
Person_ seen above is the meta model of our entity which is required for Query building. You can check this article about meta model in hibernate.

Our controller takes user query parameters as follows

Filter is the object that represent the RequestVariables.

And the service logic is as follows

So in our service logic we check if we are receiving any filter param and if so, we are creating specifications for each of them and combining it together in the end and asking dao to pull the data based on that specification logic.
The dao must implement JpaSpecificationExecutor to handle specification related queries.

The sample project codes are here

Happy specificating! 🙂