【问题标题】:Can I limit the result of JPQL to just return one result?我可以将 JPQL 的结果限制为只返回一个结果吗?
【发布时间】:2016-03-29 04:51:13
【问题描述】:

我想在存储库接口中做这样的事情(在 Spring Data JPA 中):

interface myRepository extends JpaRepository<A, Long> {
    @Query("select a from A a where a.x = :x")
    A findFirstBySomeCondition(int x);
}

但我只需要第一个结果。 (已编辑:实际查询条件非常复杂,所以我更喜欢使用 @Query 而不是 findFirst 或 findTop...)

我不想使用条件 api,因为它很冗长。

我不想使用本机查询,因为我必须手动编写查询字符串。

那么,鉴于上述限制性要求,是否还有解决方案?

谢谢!

【问题讨论】:

  • 你检查我的答案了吗?
  • findFirstworks。如果您的要求真的像您发布的那样简单,A findFirstByX(int x) 将在没有 @Query 注释的情况下工作。检查我链接到的 Spring Data JPA 文档。
  • 这是一个非常简化的示例,所以我想使用@Query 而不是findFirst
  • 那你应该改进你的问题。它现在发布的方式是文档中描述的确切用例,因此它被视为调试问题而不是特定的编程问题。

标签: spring jpa spring-data spring-data-jpa jpql


【解决方案1】:

查询方法的结果可以通过关键字first或top来限制,可以互换使用。可以将可选数值附加到 top/first 以指定要返回的最大结果大小。

interface myRepository extends JpaRepository<A, Long> {
    @Query("select a from A a where a.x = :x")
    Page<A> findFirstBySomeCondition(@Param("x") int x,Pageable pageable);
}

实现类:

Page<A> results = repository.findFirstBySomeCondition(x,new   PageRequest(0, 1));
A object = results.getContent.get(0);

【讨论】:

  • 最好返回Slice&lt;A&gt;(而不是Page&lt;A&gt;),因为它不会增加额外计数查询的开销(请参阅Spring Data JPA doc
【解决方案2】:

您可以为此使用Pageable。文档显示了使用它的不同方式:http://docs.spring.io/spring-data/jpa/docs/current/reference/html/#repositories.limit-query-result

【讨论】:

  • 所以我可以使用Pageable@Query 并将页面大小设置为1?会试试的:-)
  • 是的,同时@jackk 提供了一个带有代码的答案;)
猜你喜欢
  • 1970-01-01
  • 2013-02-14
  • 1970-01-01
  • 2012-07-08
  • 2021-05-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多