Query Repository Method Naming
Spring Data JPA provides a powerful method-naming convention for query generation. By following these conventions, developers can create readable and efficient queries without writing explicit SQL or JPQL. This article explores various query method naming strategies, including equality, similarity, comparison conditions, multiple condition expressions, sorting, and recent changes in CrudRepository.
1. Equality Condition Keywords
Exact equality is a common condition in queries. We have several options to express =
or IS
operators:
-
Append the property name without a keyword for an exact match:
1
List<User> findByName(String name);
-
Use
Is
orEquals
for readability:1 2
List<User> findByNameIs(String name); List<User> findByNameEquals(String name);
-
Express inequality with
IsNot
:1
List<User> findByNameIsNot(String name);
Spring Data JPA automatically handles null
parameters as IS NULL
. We can explicitly use IsNull
or IsNotNull
:
|
|
For boolean fields, True
and False
keywords add equality conditions:
|
|
2. Similarity Condition Keywords
For pattern-based queries:
-
Match values starting with a prefix:
1
List<User> findByNameStartingWith(String prefix);
-
Match values ending with a suffix:
1
List<User> findByNameEndingWith(String suffix);
-
Match values containing a substring:
1
List<User> findByNameContaining(String infix);
For custom patterns, use Like
:
|
|
Example usage:
|
|
3. Comparison Condition Keywords
For numeric comparisons:
|
|
To find users between two ages:
|
|
For collection-based queries:
|
|
For date comparisons:
|
|
4. Multiple Condition Expressions
We can combine conditions using And
and Or
:
|
|
And
takes precedence over Or
, following Java’s operator precedence.
For complex queries, consider using the @Query
annotation.
5. Sorting the Results
Sorting can be applied with OrderBy
:
|
|
For descending order:
|
|
6. findOne
vs. findById
in CrudRepository
Spring Boot 2.x changed findOne
to findById
:
|
|
The findById()
method is already defined in CrudRepository
, eliminating the need for custom implementations.
By following these naming conventions, we can write concise, readable, and efficient queries in Spring Data JPA.