Advertisement
Google Ad Slot: content-top
Spring Boot JPA Specifications (Specification<T>)
Spring Data JPA Specifications allow you to create dynamic queries with filtering conditions in a flexible way.
Why Use Specification<T>?
- Build dynamic queries based on user input.
- Avoid writing multiple static queries.
- Combine multiple conditions easily (
AND,OR). - Supports pagination & sorting.
Adding Dependency
Ensure you have Spring Data JPA dependency and lombok in your pom.xml:
Example Entity Class
Let's assume we have a User entity with fields: id, name, email and age
Table name : user
| id | name | age | |
|---|---|---|---|
| 1 | John | john@gmail.com | 25 |
| 2 | Mike | mike@gmail.com | 35 |
| 3 | Watson | watson@gmail.com | 40 |
| 4 | Kenny | kenny@gmail.com | 45 |
Create Specification
Each method returns a Specification<User> that dynamically applies a filtering condition.
Create Repository Using JpaSpecificationExecutor
- Spring Data JPA provides
JpaSpecificationExecutorfor dynamic queries. JpaSpecificationExecutor<User>allows dynamic querying withSpecification<User>.
Create Services
Create Controllers
Testing the REST API with Postman:
Once the application is running, test the endpoints:
Get User like name GET:http://localhost:8080/users/search?name=John
Get User by age greaterThanOrEqualTo GET:http://localhost:8080/users/search?age=40
Get User by like name or greaterThanOrEqualTo age GET:http://localhost:8080/users/search?name=John&age=40