From 40ce4c0504dbae857d21bb94f6708881d415e7a8 Mon Sep 17 00:00:00 2001 From: Jatish Khanna Date: Fri, 25 Mar 2022 12:01:15 +0530 Subject: [PATCH] [Fix] Query with(pageable) and with(Pageable.unpaged) There's a fix proposed when we want to use the same query for the pageable and unpaged instance. A typical case would be Get all the Object using the mongoTemplate from the Repository mongoTemplate.find(filterQuery.with(pageable), CustomBean.class) Get the count of all the instance but unpaged mongoTemplate.count(filterQuery.with(Pageable.unpaged()), CustomBean.class); And implementing the page instance new PageImpl<>(mongoDocumentsPaged, pageable, count); In the order of invoking with(pageable) comes first will set the parameters - "skip, limit, sort" and then invoking with(Pageable.unpaged()) won't reset them to "0, 0, Sort.unsorted()" The fix will reset 1) in the with(Pageable pageable) this.limit = 0; // default value this.skip = 0; // default value 2) in the with(Sort sort) this.sort = sort; // which will be Sort.unsorted() --- .../org/springframework/data/mongodb/core/query/Query.java | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/query/Query.java b/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/query/Query.java index 67961be900..c28ac3360f 100644 --- a/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/query/Query.java +++ b/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/query/Query.java @@ -182,7 +182,9 @@ public Query withHint(Document hint) { public Query with(Pageable pageable) { if (pageable.isUnpaged()) { - return this; + this.limit = 0; // default value + this.skip = 0; // default value + return with(pageable.getSort()); } this.limit = pageable.getPageSize(); @@ -202,6 +204,7 @@ public Query with(Sort sort) { Assert.notNull(sort, "Sort must not be null!"); if (sort.isUnsorted()) { + this.sort = sort; // Sort.unsorted() return this; }