'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.

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);


Solution 1:[1]

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.

Solution 2:[2]

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

Solution 3:[3]

You can use result.getTotalElements() to get the total number of elements.

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

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Archimedes Trajano
Solution 2 Akmal
Solution 3 ebey