Advertisement
Google Ad Slot: content-top
Spring Boot Derived Query Methods
Spring Data JPA provides Derived Query Methods, which allow you to create queries automatically based on method names without writing SQL or JPQL.
How Derived Query Methods Work?
- Spring Data JPA parses the method name and generates the corresponding SQL query.
- It follows a specific naming convention to understand what to query.
- No need to use
@Queryunless you need custom queries.
Example Entity Class
Let's assume we have a User entity with fields: id, name, email, status, and age.
Creating Derived Query Methods
Now, let's define a Spring Data JPA Repository.
Spring Data JPA Naming Keywords
Spring understands these keywords and converts them into queries:
Keyword |
Description |
Example |
|---|---|---|
findBy |
Selects records based on a field |
findByName(String name) |
And |
Combines two conditions |
findByNameAndStatus(String name, String status) |
Or |
Finds records where at least one condition matches |
findByNameOrEmail(String name, String email) |
Between |
Finds values within a range |
findByAgeBetween(int start, int end) |
LessThan |
Finds values less than a specific value |
findByAgeLessThan(int age) |
GreaterThan |
Finds values greater than a specific value |
findByAgeGreaterThan(int age) |
Like |
Finds partial matches |
findByNameLike(String name) |
Containing |
Similar to LIKE ( |
findByNameContaining(String name) |
StartingWith |
Similar to LIKE ( |
findByNameStartingWith(String prefix) |
EndingWith |
Similar to LIKE ( |
findByNameEndingWith(String suffix) |
OrderBy |
Sort results |
findByNameOrderByAgeAsc(String name) |
Not |
Negates a condition |
findByStatusNot(String status) |
In |
Matches against a list of values |
findByStatusIn(List<String> statuses) |
Using Derived Queries in a Service Class
Using Derived Queries in a Controller
Testing the REST API with Postman:
Once the application is running, test the endpoints:
Load Users http://localhost:8080/users/loadUser
Find Users by Name http://localhost:8080/users/search?name=John
Find Users Older Than 30 http://localhost:8080/users/ageGreaterThan?age=30