【问题标题】:JPQL Query Annotation with Limit and Offset带有限制和偏移的 JPQL 查询注释
【发布时间】:2012-03-14 23:29:41
【问题描述】:

我有一个存储库接口,其中包含一些使用@Query 注释的抽象方法。 现在我想为这个查询添加限制和偏移支持。

示例:

public interface ProductRepository
   extends CrudRepository<Product, Long> {

    @Query("from Product")
    List<Product> findAllProducts();
}

这样就好了

public interface ProductRepository
   extends CrudRepository<Product, Long> {

    @Query("from Product limit :limit ")
    List<Product> findAllProducts(@Param("limit") Integer limit);
}

但这不起作用。有一个解决方案,我创建了接口的实现(http://stackoverflow.com/questions/3479128/jpql-limit-number-of-results) 但我想知道是否不可能为查询添加偏移量和限制,或者是否有注释。

【问题讨论】:

  • 您为什么不简单地实现该方法并使用JPA API?注释很酷,但它们不应该取代你所有的 Java 代码。
  • 这是使用和扩展 Spring 的存储库接口的标准方式。
  • 写这个...解决根本问题的标准方法是使用PagingAndSortingRepository

标签: java jpa


【解决方案1】:

limit 不受 JPQL 支持。即使没有它,您的查询也是无效的JPQL queries(但可能是有效的 HQL - 如果您的 JPA 提供程序能够容忍,则可能会起作用)。

需要一个(部分)实现,以便您可以使用Query 接口或条件api。

【讨论】:

    【解决方案2】:

    +1 用户“他”在评论中所说的话:

    “解决根本问题的标准方法是使用 PagingAndSortingRepository”

    这是一个例子。我将排序作为额外的奖励:

    public interface ArtifactRepo extends JpaRepository<Artifact, Long> {
        Page<Artifact> findByComponentKey(String componentKey, Pageable pageable);
    }
    

    (如果您愿意,可以使用上面的@Query,但 JPQL 本身并不支持限制,正如“his”所指出的那样。)

    然后调用的时候,使用

    PageRequest pageRequest =
        new PageRequest(0, 1, Sort.Direction.DESC, "buildNumber");
    Page<Artifact> artifactsPage =
        artifactRepo.findByComponentKey(componentKey, pageRequest);
    

    你也可以看看我写的这篇博文:

    http://springinpractice.com/blog/categories/chapter-02-data/

    【讨论】:

      猜你喜欢
      • 2014-12-24
      • 1970-01-01
      • 2012-05-17
      • 1970-01-01
      • 2019-06-05
      • 2017-11-17
      • 2013-01-30
      • 1970-01-01
      • 2019-06-06
      相关资源
      最近更新 更多