Get total count rows for Pageable custom query in Spring repository

ip696 picture ip696 · Jan 30, 2018 · Viewed 13k times · Source

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?

Answer

Noixes picture Noixes · Feb 2, 2018

Try changing your object to

Page<Products> p .. 

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