问题描述
到目前为止我所知道的是 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
,CompletableFuture
等
对于您想要返回 T 集合的查询 - 您可以指定 List
, Stream
, Page
, 切片
等
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 如何执行查询 - 它将调用 getSingleResult()
在 javax.persistence.Query
接口,如果有多个对象满足条件,将抛出异常
.
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.
findBydepartmentId
返回单条记录的依据是什么?
基于有一个带有该Id的对象,否则会抛出异常.
On the basis that there's a single object with that Id, otherwise it will throw an exception.
何时或为什么不应该使用 findBy
代替 findOneBy
?
两者含义不同,不可互换.
Those two have different meanings and are not interchangeable.
findOneBy
总是导致 getSingleResult()
被调用.
findOneBy
always results in getSingleResult()
being invoked.
findBy
根据返回类型具有不同的行为 - 根据上面给出的定义.
findBy
has different behavior depending on the return type - as per the definitions given above.
这篇关于Spring数据JPA中findBy和findOneBy的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!