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