Spring Data JPA。从Pageable获取所有页面

5

我有一个SpringBoot应用程序,其中有一个接口继承自CrudRepository

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

我想知道是否可以从对象Pageable中获取总页数。

2个回答

4
您可以使用返回总元素数的Page<T>接口。

long - getTotalElements()

返回元素的总数量。

您可以在文档中找到更多信息: PagePageImpl
在您的示例中,它应该像这样工作:
@Query("select cps from HotelPriceSummary cps where cps.price > 5 and cps.profilePercentage >= 70 ")
Page<HotelPriceSummary> findMine(Pageable pageable);

3

您应该从PagingAndSortingRepository扩展您的存储库,而不是CrudRepository。然后方法查询应为:

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

接下来,您可以从服务(或任何您想要的地方)使用查询,然后在响应中调用getTotalPages()。例如:

int page = 0, pageSize = 10;    
Page<HostelPriceSummary> response = myRepo.findMine(PageRequest.of(page, pageSize));
int numberOfPages =  response.getTotalPages();

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接