Basic Tutorial
Queries
Spring Data JPA provides Derived Query Methods, which allow you to create queries automatically based on method names without writing SQL or JPQL.
@Query unless you need custom queries.Let's assume we have a User entity with fields: id, name, email, status, and age.
Now, let's define a Spring Data JPA Repository.
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) |
Once the application is running, test the endpoints:
http://localhost:8080/users/loadUser
http://localhost:8080/users/search?name=John
http://localhost:8080/users/ageGreaterThan?age=30