简体   繁体   English

如何获取从可分页 JPA 查询生成的数据总数

[英]How to get the total count of data generated from pageable JPA query

How to get the count of items generated by the query.如何获取查询生成的项目数。 Suppose let the query generates 12 items.假设让查询生成 12 个项目。

product.size() -> generates " 12 "; 

But since I am paging it by 4 items per page, when I do但由于我每页按 4 个项目分页,所以当我这样做时

product.size() -> generates " 4 "; 

My question is how to get the total count as 12 and not 4 with respect to the page.我的问题是如何将页面的总数设为 12 而不是 4。

Service服务

public SearchPage productSearch(String query {
           Pageable pageable=PageRequest.of(0,4);
           List<Products> products=repository.getProductByQuery(query,pageable);      
    }

Repository存储库

@Query("select DISTINCT p1 from Products p1  where CONCAT(p1.title,p1.category) like %:query%")
 List<Products> getProductByQuery(@Param("query") String query, Pageable pageable);

You can add this to your repository:您可以将其添加到您的存储库:

List<Products> findAll();

then you can use:那么你可以使用:

List<Products> products=repository.findAll();
int count = products.size();

From your question I suppose you are using Spring Data JPA.根据您的问题,我想您正在使用 Spring 数据 JPA。 In a nutshell, yes your method might work, however, spring data returns you (when you query data with Pageable object) either a Page object or a Slice.简而言之,是的,您的方法可能有效,但是,spring 数据(当您使用 Pageable 对象查询数据时)返回页面 object 或切片。 I believe they both contain the total number of elements.我相信它们都包含元素的总数。 Furthermore, they give you additional information of how many total items are there as well as which page you are at.此外,它们还会为您提供有关总共有多少项目以及您在哪个页面的附加信息。 Hope this answers your question.希望这能回答你的问题。 In case it does not, refer to https://www.baeldung.com/rest-api-pagination-in-spring如果没有,请参阅https://www.baeldung.com/rest-api-pagination-in-spring

You can use result.getTotalElements() to get the total number of elements.您可以使用 result.getTotalElements() 来获取元素的总数。

List<Products> products=repository.getProductByQuery(query,pageable).getTotalElements();  

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM