Difference between findBy and findOneBy in Spring data JPA

Arun Gowda picture Arun Gowda · Aug 31, 2017 · Viewed 25.5k times · Source

All i know so far is that FindBy can return multiple results while FindOneBy will return a single result or null when we use it the following way.

List<Department> findByDepartmentName(String name);
Department findOneByDepartmentId(Long Id);

now, my question is, can i use findBy this way?

Department  findByDepartmentId(Long Id);

If yes,

  • Lets assume there are multiple records for given Id.
  • On what basis does findBydepartmentId return a single record?

Finally, When or Why should i not use findBy in place of findOneBy?

Answer

hovanessyan picture hovanessyan · Feb 11, 2018

Can I use findBy this way? Department findByDepartmentId(Long Id);

Yes, this syntax is technically correct from Spring JPA point of view. Although Spring JPA infers what you're trying to achieve with your query looking at the return type as well.

Basically these are the cases for return types:

That being said, your query definition:

Department findByDepartmentId(Long Id);

means that you expect a single result (because you've specified Entity T as a return type). This will reflect on how Spring JPA executes the query - it will call getSingleResult() on the javax.persistence.Query interface, which will throw an exception if more than one objects satisfy the criteria.

On what basis does findBydepartmentId return a single record?

On the basis that there's a single object with that Id, otherwise it will throw an exception.

When or Why should i not use findBy in place of findOneBy?

Those two have different meanings and are not interchangeable.

findOneBy always results in getSingleResult() being invoked.

findBy has different behavior depending on the return type - as per the definitions given above.