perf(api): Avoid unnecessary DISTINCT in paginated book queries (#2844)

This commit is contained in:
Alex
2026-10-02 14:01:54 +01:00
committed by GitHub
parent 8a7c03b291
commit 6a45a453f5
@@ -1,5 +1,6 @@
package org.booklore.service.book; package org.booklore.service.book;
import jakarta.persistence.criteria.From;
import lombok.RequiredArgsConstructor; import lombok.RequiredArgsConstructor;
import org.booklore.app.specification.AppBookSpecification; import org.booklore.app.specification.AppBookSpecification;
import org.booklore.mapper.v2.BookMapperV2; import org.booklore.mapper.v2.BookMapperV2;
@@ -58,17 +59,17 @@ public class BookQueryService {
private Specification<BookEntity> distinct(Specification<BookEntity> filter) { private Specification<BookEntity> distinct(Specification<BookEntity> filter) {
return (root, query, cb) -> { return (root, query, cb) -> {
// We need to query distinct because otherwise the `JOIN` + `LIMIT` cause the page sizes to be wrong. var predicate = filter.toPredicate(root, query, cb);
// query.distinct(query.isDistinct() || hasCollectionJoin(root));
// I've tried a few ways to just get only what we need - distinct IDs from the repository. return predicate;
// 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);
}; };
} }
private static boolean hasCollectionJoin(From<?, ?> from) {
return from.getJoins().stream().anyMatch(join ->
join.getAttribute().isCollection() || hasCollectionJoin(join));
}
public Page<Book> findBooksPaged(Specification<BookEntity> spec, Pageable pageable, Long userId) { public Page<Book> findBooksPaged(Specification<BookEntity> spec, Pageable pageable, Long userId) {
Page<BookEntity> page = bookRepository.findAll(distinct(spec), pageable); Page<BookEntity> page = bookRepository.findAll(distinct(spec), pageable);
Map<Long, BookEntity> booksById = bookRepository Map<Long, BookEntity> booksById = bookRepository