Spring Data JPA与findBy / findAllBy的区别

时间:2016-05-16 12:07:23

标签: java spring spring-data spring-data-jpa

在以下之间使用Spring Data JPA关键字时是否有任何区别:

<a href="<?php echo site_url()."/sport/football/"?>" onclick="homepage_football()">
 <a href="<?php echo site_url()."/sport/basketball/"?>" onclick="homepage_basketball()">
 <a href="<?php echo site_url()."/sport/netball/"?>" onclick="homepage_netball()">

List<SomeEntity> findBySomeCondition();

4 个答案:

答案 0 :(得分:63)

不,它们之间没有区别,它们将执行完全相同的查询,当从方法名称派生查询时,Spring Data会忽略All部分。唯一重要的一点是By关键字,其后面的任何内容都被视为字段名称(除了OrderBy之外的其他关键字,这些关键字可能导致一些奇怪的方法名称,如{{1} })。

这意味着这样的事情完全有效:

findAllByOrderByIdAsc

将执行完全相同的SQL查询:

List<SomeEntity> findAnythingYouWantToPutHereBySomeCondition();

List<SomeEntity> findBySomeCondition();

更新:我从未在文档中看到任何关于此行为的官方说明,但在recent blog post中有关即将发布的Spring Data(Kay)2.0版本的内容已经解释过:< / p>

  

Spring Data的方法解析使用前缀关键字,如List<SomeEntity> findAllBySomeCondition(); findexistscount以及终止delete关键字。您在Byfind之间放置的所有内容都会使您的方法名称更具表现力,并且不会影响查询派生。

答案 1 :(得分:0)

一个区别是使用findAllBy时,使用了Hibernate过滤器(来自org.hibernate.annotations的@Filters),因此使用了不同的sql。

答案 2 :(得分:0)

为了说明区别,让我们看一下这两个函数:

1.  select policy.id, policy.role from policy where (policy.role in (? , ? , ? , ?))

第一个函数生成的查询:

2. select policy.id, policy.role from policy where (policy.role in (? , ? , ? , ?))

第二个函数生成的查询:

# specific path build
trigger:
  branches:
    include:
    - master
    - releases/*
  paths:
    include:
    - docs
    exclude:
    - docs/README.md

结论:显然,如果我们查看两个函数生成的查询。我们可以清楚地看到,两个函数定义没有区别,它们执行完全相同的查询。

答案 3 :(得分:-2)

如果我们想要按名称或其他标准找到findByFirstName(String firstName);

,则会使用findBy方法

findAll方法通常通过提供规范

来查找
List<T> findAll(Specification<T> spec);

请参阅以下文档以获得更清晰:

http://docs.spring.io/spring-data/jpa/docs/1.4.3.RELEASE/reference/html/jpa.repositories.html