带有限制和偏移的JPQL查询注释

时间:2012-02-24 14:03:47

标签: java jpa

我有一个存储库接口,其中包含一些使用@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) 但我想知道是否有可能在查询中添加偏移和限制,或者是否有注释。

2 个答案:

答案 0 :(得分:11)

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

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

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

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

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

然后在调用时,使用

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/

答案 1 :(得分:6)

JPQL不支持

limit。即使没有它,您的查询也无效JPQL queries(但可能是有效的HQL - 如果您的JPA提供商能够容忍,则可能有效)。

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

相关问题