Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

2 Answers

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.

like image 122
Archimedes Trajano Avatar answered Oct 26 '25 05:10

Archimedes Trajano


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

List<Products> products=repository.getProductByQuery(query,pageable).getTotalElements();  
like image 20
ebey Avatar answered Oct 26 '25 04:10

ebey



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!