Can I use findBy this way? Department findByDepartmentId (long identifier);
Yes, this syntax is technically correct from the perspective of JPA Spring. Although Spring JPA indicates what you are trying to achieve, and your request also looks at the return type.
These are mainly cases for return types:
with your request you want to return a single value - you can specify the base type, Entity T , Optional<T> , CompletableFuture<T> , etc.
with your request you want to return the collection T - you can specify List<T> , Stream<T> , Page<T> , Slice<T> , etc.
As the saying goes, the definition of your request is:
Department findByDepartmentId(Long Id);
means that you expect a single result (because you specified a single Entity as the return type). This will affect how Spring JPA executes the request - it will call getSingleResult () in the javax.persistence.Query interface, which will javax.persistence.Query exception if several criteria meet the criteria.
On what basis do findBydepartmentId return a single record?
Based on the fact that there is one object with this identifier, otherwise it throws an exception.
When or why should I not use findBy instead of findOneBy?
These two have different meanings and are not interchangeable.
findOneBy always results in a call to getSingleResult ().
findBy has different behavior depending on the type of return - according to the definitions above.
source share