Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get total count rows for Pageable custom query in Spring repository

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?

like image 263
ip696 Avatar asked Jan 30 '18 07:01

ip696


People also ask

How do you count rows in spring boot?

If you want to know the total number of rows available in the entity table, use the count derived method of the CrudRepository interface. For example, the following getCustomerCount method retrieves the number of entities available in the table using the method count.

How can I apply pagination in JPA?

The simplest way to implement pagination is to use the Java Query Language – create a query and configure it via setMaxResults and setFirstResult: Query query = entityManager. createQuery("From Foo"); int pageNumber = 1; int pageSize = 10; query.

How does Spring Pageable work?

In Spring Data, if we need to return a few results from the complete data set, we can use any Pageable repository method, as it will always return a Page. The results will be returned based on the page number, page size, and sorting direction.


1 Answers

Try changing your object to

Page<Products> p .. 

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

like image 134
Noixes Avatar answered Sep 25 '22 19:09

Noixes