Difference between findBy and findOneBy in Spring data JPA

后端 未结 3 780
半阙折子戏
半阙折子戏 2020-12-28 15:43

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

        
相关标签:
3条回答
  • 2020-12-28 16:14

    findOneByXX will ensure that there is only one or no value, if there are 2 values an exception will be thrown.

    However findByXX doesn't make this check of uniqueness.

    0 讨论(0)
  • 2020-12-28 16:24

    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:

    • with your query you want to return a single value - you can specify basic type, Entity T, Optional<T>, CompletableFuture<T> etc.

    • with your query you want to return a collection of T - you can specify List<T>, Stream<T>, Page<T>, Slice<T> etc.

    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.

    0 讨论(0)
  • 2020-12-28 16:31

    I have done some tests and Spring Data ignore all characters between the method (find, delete,...) and By.

    In https://github.com/spring-projects/spring-data-commons/blob/14d5747f68737bb44441dc511cf16393d9d85dc8/src/main/java/org/springframework/data/repository/query/parser/PartTree.java#L65 it is the \p{Lu}.*? part.

    Spring Data only use return type to decide how handle responses.

    So it is possible to define these following methods even if it is not correct semantically.

    Department findAllByDepartmentId(Long Id);
    List<Department> findOneByDepartmentName(String name);
    
    0 讨论(0)
提交回复
热议问题