问题描述
到目前为止,我只知道FindBy可以返回多个结果,而当我们按以下方式使用它时,FindOneBy将返回一个结果或null.
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);
现在,我的问题是,我可以这样使用findBy吗?
now, my question is, can i use findBy this way?
Department findByDepartmentId(Long Id);
如果是,
- 让我们假设给定ID有多个记录.
- findBydepartmentId 在什么基础上返回单个记录?
- Lets assume there are multiple records for given Id.
- On what basis does findBydepartmentId return a single record?
最后,什么时候或为什么我不应该使用findBy代替findOneBy?
Finally, When or Why should i not use findBy in place of findOneBy?
推荐答案
是的,从Spring JPA的角度来看,此语法在技术上是正确的.尽管Spring JPA还会通过查看返回类型来推断您要通过查询实现的目标.
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:
-
与查询一起您要返回一个值-您可以指定
basic type
,Entity T
,Optional<T>
,CompletableFuture<T>
等.
with your query you want to return a single value - you can specify
basic type
,Entity T
,Optional<T>
,CompletableFuture<T>
etc.
使用您的查询要返回T的集合-您可以指定 List<T>
, Stream<T>
, Page<T>
, Slice<T>
等.
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);
表示您希望得到一个结果(因为您已将Entity T
指定为返回类型).这将反映Spring JPA如何执行查询-它将调用 javax.persistence.Query
上的noreferrer> getSingleResult()
界面,如果多个对象满足条件,则会抛出exception
.
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.
基于具有该ID的单个对象,否则它将引发异常.
On the basis that there's a single object with that Id, otherwise it will throw an exception.
这两个具有不同的含义,并且不能互换.
Those two have different meanings and are not interchangeable.
findBy
具有不同的行为,具体取决于返回类型-根据上面给出的定义.
findBy
has different behavior depending on the return type - as per the definitions given above.
这篇关于Spring Data JPA中findBy和findOneBy之间的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!