From 6a45a453f5a07c369b681a83a3e7e3607d0d8f4c Mon Sep 17 00:00:00 2001 From: Alex <25013571+alexhb1@users.noreply.github.com> Date: Fri, 2 Oct 2026 14:01:54 +0100 Subject: [PATCH] perf(api): Avoid unnecessary `DISTINCT` in paginated book queries (#2844) --- .../booklore/service/book/BookQueryService.java | 17 +++++++++-------- 1 file changed, 9 insertions(+), 8 deletions(-) diff --git a/backend/src/main/java/org/booklore/service/book/BookQueryService.java b/backend/src/main/java/org/booklore/service/book/BookQueryService.java index 9bd74c3a7..16427c155 100644 --- a/backend/src/main/java/org/booklore/service/book/BookQueryService.java +++ b/backend/src/main/java/org/booklore/service/book/BookQueryService.java @@ -1,5 +1,6 @@ package org.booklore.service.book; +import jakarta.persistence.criteria.From; import lombok.RequiredArgsConstructor; import org.booklore.app.specification.AppBookSpecification; import org.booklore.mapper.v2.BookMapperV2; @@ -58,17 +59,17 @@ public class BookQueryService { private Specification distinct(Specification filter) { return (root, query, cb) -> { - // We need to query distinct because otherwise the `JOIN` + `LIMIT` cause the page sizes to be wrong. - // - // I've tried a few ways to just get only what we need - distinct IDs from the repository. - // With Projections, we ran into issues with the order by not getting applied. I'm sure - // there's a better way but right now this works well enough, even though it over-fetches. - - query.distinct(true); - return filter.toPredicate(root, query, cb); + var predicate = filter.toPredicate(root, query, cb); + query.distinct(query.isDistinct() || hasCollectionJoin(root)); + return predicate; }; } + private static boolean hasCollectionJoin(From from) { + return from.getJoins().stream().anyMatch(join -> + join.getAttribute().isCollection() || hasCollectionJoin(join)); + } + public Page findBooksPaged(Specification spec, Pageable pageable, Long userId) { Page page = bookRepository.findAll(distinct(spec), pageable); Map booksById = bookRepository