Reputation:
How to get the count of items generated by the query. Suppose let the query generates 12 items.
product.size() -> generates " 12 ";
But since I am paging it by 4 items per page, when I do
product.size() -> generates " 4 ";
My question is how to get the total count as 12 and not 4 with respect to the page.
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);
Upvotes: 4
Views: 16031
Reputation: 41240
Instead of using List
as your return type use org.springframework.data.domain.Page
which will provide you getTotalElements()
and other paging information including the original Pageable
request.
Upvotes: 6
Reputation: 153
You can use result.getTotalElements() to get the total number of elements.
List<Products> products=repository.getProductByQuery(query,pageable).getTotalElements();
Upvotes: 4
Reputation: 395
From your question I suppose you are using Spring Data 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. 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
Upvotes: 0