Spring Data Mongo Templateのページネーション
Spring Data Mongo Templateでページネーションを追加する方法を説明します。
デフォルトでは、Spring Mongo Templateにはページ単位で検索する方法がありません。すべてのレコードを検索して返します。
MongoTemplate
次のようにページネーションを追加します。
Pageable pageable = PageRequest.of(0, 10);
Query query = new Query().with(pageable);
// 必要なクエリを追加します。
List<User> list = mongoTemplate.find(query, User.class, "user");
Page<User> page = PageableExecutionUtils.getPage(
list,
pageable,
() -> mongoTemplate.count(query, Patient.class));
ReactiveMongoTemplate
ReactiveMongoTemplateを使用する場合は、次のようにページネーションを追加します。
Pageable pageable = PageRequest.of(0, 10);
Query query = new Query().with(pageable);
// 必要なクエリを追加します。
Mono<List<User>> list = reactiveMongoTemplate.find(query, User.class, "user").collectList();
Mono<Long> count = reactiveMongoTemplate.count(query, ActiveUser.class);
Page<User> userPage = list.zipWith(count)
.map(tuple -> PageableExecutionUtils.getPage(tuple.getT1(), param.getPageable(), tuple::getT2));