AdSense

網頁

2019/12/30

Spring Data MongoDB 分頁查詢 page query

在Spring Boot中利用Spring Data MongoDB做分頁查詢的方法如下。


請先參考Spring Boot 2 + Spring Data MongoDB + MongoDB 簡單範例建立專案及MongoDB中的資料。

MongoDB中的customers資料如下。

{
    "_id" : ObjectId("5d5d54e8bde3f3783ed04996"),
    "name" : "John",
    "age" : 28
}

{
    "_id" : ObjectId("5d5d75e9e646b627cccf2c77"),
    "name" : "Mary",
    "age" : 23,
    "_class" : "com.abc.demo.entity.Customer"
}

在用來存取MongoDB的MongoRepository介面CustomerRepo新增分頁查詢的方法findByAge(int age, Pageable pageable),並返回分頁查詢結果Page<Customer>。Spring Data會自動對有分頁參數Pageable的查詢方法進行分頁查詢。

package com.abc.demo.repo;

import java.util.List;
import java.util.Optional;

import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.mongodb.repository.MongoRepository;

import com.abc.demo.entity.Customer;

public interface CustomerRepo extends MongoRepository<Customer, String> {
    
    public Optional<Customer> findByName(String name);
    public List<Customer> findByAge(int age);
    
    public Page<Customer> findByAge(int age, Pageable pageable); //<-- 分頁查詢方法

}

查詢時使用PageRequest.of()產生分頁查詢條件。

int age = 23;
int page = 0;  // 查詢頁數,從0開始為第一頁
int size = 10; // 每頁筆數,設為每頁10筆

PageRequest pageable = PageRequest.of(page, size, Sort.by("age").descending());
                                
Page<Customer> pageResult = customerRepo.findByAge(age, pageable);

System.out.println(pageResult.getTotalPages()); // 1 全部頁數
System.out.println(pageResult.getTotalElements()); // 1 全部筆數 
System.out.println(pageResult.getSize()); // 10 每頁筆數
System.out.println(pageResult.getNumber()); // 0 目前頁號,0為第一頁
System.out.println(pageResult.getNumberOfElements()); // 1 目前頁筆數

ObjectMapper mapper = new ObjectMapper();
String jsonString = mapper.writeValueAsString(pageResult.getContent()); // 轉成json字串

System.out.println(jsonString); // [{"id":"5d5d75e9e646b627cccf2c77","name":"Mary","age":23}]



參考:

沒有留言:

AdSense