[英]Get total count rows for Pageable custom query in Spring repository
[英]How to get the total count of data generated from pageable JPA query
如何獲取查詢生成的項目數。 假設讓查詢生成 12 個項目。
product.size() -> generates " 12 ";
但由於我每頁按 4 個項目分頁,所以當我這樣做時
product.size() -> generates " 4 ";
我的問題是如何將頁面的總數設為 12 而不是 4。
服務
public SearchPage productSearch(String query {
Pageable pageable=PageRequest.of(0,4);
List<Products> products=repository.getProductByQuery(query,pageable);
}
存儲庫
@Query("select DISTINCT p1 from Products p1 where CONCAT(p1.title,p1.category) like %:query%")
List<Products> getProductByQuery(@Param("query") String query, Pageable pageable);
您可以將其添加到您的存儲庫:
List<Products> findAll();
那么你可以使用:
List<Products> products=repository.findAll();
int count = products.size();
根據您的問題,我想您正在使用 Spring 數據 JPA。 簡而言之,是的,您的方法可能有效,但是,spring 數據(當您使用 Pageable 對象查詢數據時)返回頁面 object 或切片。 我相信它們都包含元素的總數。 此外,它們還會為您提供有關總共有多少項目以及您在哪個頁面的附加信息。 希望這能回答你的問題。 如果沒有,請參閱https://www.baeldung.com/rest-api-pagination-in-spring
您可以使用 result.getTotalElements() 來獲取元素的總數。
List<Products> products=repository.getProductByQuery(query,pageable).getTotalElements();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.