Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring Data JPA. Getting all pages from Pageable

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

like image 551
Nunyet de Can Calçada Avatar asked Mar 20 '18 12:03

Nunyet de Can Calçada


2 Answers

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);
like image 54
Patrick Avatar answered Oct 13 '22 21:10

Patrick


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();
like image 40
Ariel Kohan Avatar answered Oct 13 '22 21:10

Ariel Kohan