5

I have a SpringBoot app and an interface that extends from CrudRepository

@Query("select cps from HotelPriceSummary cps where cps.price > 5 and cps.profilePercentage >= 70 ")
List<HotelPriceSummary> findMine(Pageable pageable);

I would like to know if it is possible to get the total number of pages from the object Pageable

Patrick
  • 12,336
  • 15
  • 73
  • 115
Nuñito Calzada
  • 4,394
  • 47
  • 174
  • 301

2 Answers2

4

You can use the Page<T> Interface which returns the total elements.

long - getTotalElements()

Returns the total amount of elements.

You can find more in the docs: Page and PageImpl.

In your example it should work like that:

@Query("select cps from HotelPriceSummary cps where cps.price > 5 and cps.profilePercentage >= 70 ")
Page<HotelPriceSummary> findMine(Pageable pageable);
Patrick
  • 12,336
  • 15
  • 73
  • 115
3

You should extend your repository from PagingAndSortingRepository instead of CrudRepository. Then the method query should be:

@Query("select cps from HotelPriceSummary cps where cps.price > 5 and cps.profilePercentage >= 70 ")
Page<HotelPriceSummary> findMine(Pageable pageable);

After that, you can use the query from a service (or whatever you want) and then getTotalPages() in the response. Example:

int page = 0, pageSize = 10;    
Page<HostelPriceSummary> response = myRepo.findMine(PageRequest.of(page, pageSize));
int numberOfPages =  response.getTotalPages();
Ariel Kohan
  • 674
  • 4
  • 15