Nuñito Calzada
Nuñito Calzada

Reputation: 2056

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

Upvotes: 5

Views: 8749

Answers (2)

Ariel Kohan
Ariel Kohan

Reputation: 694

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();

Upvotes: 3

Patrick
Patrick

Reputation: 12734

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);

Upvotes: 4

Related Questions