Is there any difference when using Spring Data JPA keywords between:
List<SomeEntity> findBySomeCondition();
and
List<SomeEntity> findAllBySomeCondition();
CrudRepository mainly provides CRUD operations. PagingAndSortingRepository provide methods to perform pagination and sorting of records. JpaRepository provides JPA related methods such as flushing the persistence context and deleting of records in batch.
As a consequence, findById() returns the actual object and getById returns a reference of the entity.
In Spring Data JPA Repository is a top-level interface in hierarchy. The saveAll() method has been defined as below. Iterable saveAll(Iterable entities) – used to save multiple entities. The saveAll() method internally annotated with @Transactional.
No, there is no difference between them, they will execute exactly the same query, the All
part is ignored by Spring Data when deriving the query from the method name. The only important bit is the By
keyword, anything following it is treated as a field name (with the exception of other keywords like OrderBy
which incidentially can lead to some strange looking method names like findAllByOrderByIdAsc
).
This means something like this is perfectly valid:
List<SomeEntity> findAnythingYouWantToPutHereBySomeCondition();
And will execute exactly the same SQL query as:
List<SomeEntity> findBySomeCondition();
or
List<SomeEntity> findAllBySomeCondition();
The documentation for the 2.3.6 release of Spring Data discusses this feature:
Any text between
find
(or other introducing keywords) andBy
is considered to be descriptive unless using one of the result-limiting keywords such as aDistinct
to set a distinct flag on the query to be created orTop
/First
to limit query results.
The purpose of feature was explained in a blog post about the then-upcoming 2.0 release of Spring Data:
Spring Data’s method parsing uses prefix keywords like
find
,exists
,count
, anddelete
and a terminatingBy
keyword. Everything you put in betweenfind
andBy
makes your method name more expressive and does not affect query derivation.
To illustrate the difference lets look at the two functions:
1. Set<Policy> findAllByRoleIn(Iterable<Role> role); 2. Set<Policy> findByRoleIn(Iterable<Role> role);
The query generated by 1st function:
1. select policy.id, policy.role from policy where (policy.role in (? , ? , ? , ?))
The query generated by 2nd function:
2. select policy.id, policy.role from policy where (policy.role in (? , ? , ? , ?))
Conclusion: Clearly, if we look at the queries generated by both functions. We can clearly see, there is no difference between the two function definitions, they execute exactly the same query.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With