15

I implement pagination like this:

List<Products> products = productRepository.findAllProducts(productsRequest.getInitiatorType(), "ACTIVE",
      new PageRequest(page, 100, Sort.Direction.DESC, "insertDate"));

But how can I get Total size for this query? Only duplicate query like this?

  @Query("SELECT t FROM Products t WHERE t.isApproved = true AND t.partnerId = ?1 AND t.categories.status = ?2")
  List<OpcClProducts> findAllOpcClProducts(String senderId, String status, Pageable pageable);


  @Query("SELECT COUNT(t) FROM Products t WHERE t.isApproved = true AND t.partnerId = ?1 AND t.categories.status = ?2")
  long getTotalCount(String senderId, String status);

And call 2 query: for totalCount and for data?

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
ip696
  • 6,574
  • 12
  • 65
  • 128

1 Answers1

22

Try changing your object to

Page<Products> p .. 

p should have the information you are looking for. :) (Posted here because they wanted me to) ^^'

rjdkolb
  • 10,377
  • 11
  • 69
  • 89
Noixes
  • 1,158
  • 12
  • 25
  • 1
    I haven't checked it out, but I believe it's the right answer. +1 – Andrew Tobilko Feb 02 '18 at 12:58
  • 1
    page.getTotalElements() will give you number of rows returned by query page.getTotalPages() will give you number of pages with respect to page size (item per page you configured) – Hus Mukh Jul 01 '20 at 02:12
  • absolutely useful information that came first in my search results... – aswzen Sep 03 '20 at 05:33
  • Using spring boot data jdbc, if your interface extends `PagingAndSortingRepository` and the query returns more than one result, you get `org.springframework.dao.IncorrectResultSizeDataAccessException: Incorrect result size: expected 1, actual 50` – jbaranski Dec 29 '20 at 16:44