Spring › JPA

Avoiding in-memory paging with JPA collection fetch joins

Reproducing Hibernate 6.4's HHH90003004 in-memory pagination issue and measuring query counts, rows read, and heap allocation with ID-first and batch fetching.

Avoiding in-memory paging with JPA collection fetch joins

I added Pageable to a join fetch query loading posts with their comments and ended up reading 1 million comment rows just to build a 10-item page. This post reproduces what Hibernate 6.4’s HHH90003004 warning actually does and compares query counts, rows scanned, and heap allocation across ID-first paging and batch fetching.

Tested on Spring Boot 3.2.3, Hibernate ORM 6.4.4.Final, Kotlin 1.9.22, JDK 21, and PostgreSQL 16.2. I ran all benchmarks locally on a 12-core, 32GB RAM machine (Windows with Docker Desktop/WSL2), taking the median of 5 runs after 3 warm-ups per scenario.

The problem

While building a board API for a study project, I needed a paginated list endpoint returning 10 posts along with each post’s comment count. To avoid the N+1 query problem, I wrote a repository method combining a collection join fetch with Spring Data JPA’s Pageable.

1
2
3
4
5
6
// src/main/kotlin/lab/PostRepository.kt
@Query(
    value = "select p from Post p join fetch p.comments",
    countQuery = "select count(p) from Post p",
)
fun findPageWithComments(pageable: Pageable): Page<Post>

At first glance, the endpoint returned the exact 10 posts I expected. When I checked the application logs, though, Hibernate had printed a single warning line:

1
WARN --- [main] org.hibernate.orm.query : HHH90003004: firstResult/maxResults specified with collection fetch; applying in memory

I turned org.hibernate.SQL up to DEBUG to inspect the generated query. Neither LIMIT nor OFFSET appeared anywhere in the SQL:

1
2
3
select p1_0.id,c1_0.post_id,c1_0.id,c1_0.content,p1_0.title
from post p1_0 join comment c1_0 on p1_0.id=c1_0.post_id
order by p1_0.id

Even though the API only asked for 10 posts, PostgreSQL scanned and returned every single joined row in the table.

Root cause

Joining a one-to-many collection expands the SQL result set from one row per post to one row per comment. If Hibernate appended LIMIT 10 directly to that SQL query, PostgreSQL would return 10 comment rows instead of 10 posts. A single post with 10 comments would consume the entire page, or worse, a post’s comments collection would be partially truncated and out of sync with the database.

To preserve entity integrity, Hibernate abandons SQL-level pagination whenever a query combines a collection fetch with pagination limits. Instead, it executes the unbounded join, hydrates the entire result set into entity graphs on the JVM heap, deduplicates parent entities, and slices the requested firstResult to maxResults range in Java memory.

Inside Hibernate 6.4, QuerySqmImpl checks two conditions before executing a query: whether pagination limits are set and whether the query contains a collection fetch. That check covers both explicit JPQL join fetch clauses and collection associations loaded through an @EntityGraph. When both conditions hold, Hibernate logs HHH90003004 and drops the SQL limit. If you set hibernate.query.fail_on_pagination_over_collection_fetch=true, Hibernate throws an exception instead of silently falling back to memory.

flowchart TD
    A["Pageable request (10 posts)"] --> B{"Contains collection fetch?"}
    B -->|"No"| C["Apply SQL offset / fetch first"]
    B -->|"Yes"| D["Run full join without LIMIT"]
    D --> E["Hydrate all rows into entities"]
    E --> F["Slice 10 posts in JVM memory"]

Swapping JPQL join fetch for @EntityGraph(attributePaths = ["comments"]) triggered the exact same warning. The only difference in the generated SQL was left join instead of join—the number of rows read from PostgreSQL and the heap bytes allocated were identical. An entity graph isn’t a workaround; it’s just a different syntax for the same collection fetch.

Two ways to fix it

To keep pagination in the database without triggering N+1 queries, I compared two standard alternatives:

  1. Two-step ID-first paging: Page only the parent Post IDs in SQL, then run a second join fetch query constrained by where p.id in :ids.
  2. Batch fetching: Page the parent Post entities directly without joining comments, and let Hibernate load the lazy collection in one batched query using default_batch_fetch_size.

Here is the minimal setup I used to reproduce and compare both approaches.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
// build.gradle.kts
plugins {
    id("org.springframework.boot") version "3.2.3"
    id("io.spring.dependency-management") version "1.1.4"
    kotlin("jvm") version "1.9.22"
    kotlin("plugin.spring") version "1.9.22"
    kotlin("plugin.jpa") version "1.9.22"
}

dependencies {
    implementation("org.springframework.boot:spring-boot-starter-data-jpa")
    implementation("org.jetbrains.kotlin:kotlin-reflect")
    runtimeOnly("org.postgresql:postgresql")
}
1
2
3
4
5
6
7
8
9
# src/main/resources/application.yml
spring:
  jpa:
    open-in-view: false
    properties:
      hibernate:
        default_batch_fetch_size: 100
        # Fail fast in dev/test instead of silently paging in memory
        query.fail_on_pagination_over_collection_fetch: true
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
// src/main/kotlin/lab/PostRepository.kt
package lab

import org.springframework.data.domain.Page
import org.springframework.data.domain.Pageable
import org.springframework.data.jpa.repository.JpaRepository
import org.springframework.data.jpa.repository.Query

interface PostRepository : JpaRepository<Post, Long> {

    @Query(value = "select p.id from Post p", countQuery = "select count(p) from Post p")
    fun findIdPage(pageable: Pageable): Page<Long>

    @Query("select distinct p from Post p join fetch p.comments where p.id in :ids order by p.id")
    fun findAllWithCommentsByIdIn(ids: List<Long>): List<Post>

    @Query(value = "select p from Post p", countQuery = "select count(p) from Post p")
    fun findPagePlain(pageable: Pageable): Page<Post>
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
// src/main/kotlin/lab/PostQueryService.kt
package lab

import org.springframework.data.domain.PageImpl
import org.springframework.data.domain.PageRequest
import org.springframework.data.domain.Sort
import org.springframework.stereotype.Service
import org.springframework.transaction.annotation.Transactional

data class PostSummary(val id: Long, val title: String, val commentCount: Int)

@Service
@Transactional(readOnly = true)
class PostQueryService(private val postRepository: PostRepository) {

    private fun pageable(page: Int) = PageRequest.of(page, 10, Sort.by("id"))

    // Step 1: page IDs in SQL, Step 2: fetch join with IN clause
    fun idFirstPaging(page: Int): PageImpl<PostSummary> {
        val idPage = postRepository.findIdPage(pageable(page))
        val posts = postRepository.findAllWithCommentsByIdIn(idPage.content)
        return PageImpl(posts.map(::toSummary), idPage.pageable, idPage.totalElements)
    }

    // Page parent entities only, then load comments via batch fetch
    fun batchFetchPaging(page: Int) =
        postRepository.findPagePlain(pageable(page)).map(::toSummary)

    private fun toSummary(p: Post) = PostSummary(p.id, p.title, p.comments.size)
}

When I inspected the SQL generated by Hibernate 6.4 for batch fetching on PostgreSQL, I noticed it bound a single array parameter (= any (?)) instead of expanding an in (?, ?, ...) list:

1
2
select p1_0.id,p1_0.title from post p1_0 order by p1_0.id offset ? rows fetch first ? rows only
select c1_0.post_id,c1_0.id,c1_0.content from comment c1_0 where c1_0.post_id = any (?)

Because the SQL text stays identical regardless of how many parent IDs are on the page, PostgreSQL and the JDBC driver can reuse the same prepared statement plan cleanly.

Benchmark results

I seeded the database with N posts and 10 comments per post (100-character body each), then fetched the first page of 10 posts. I measured total database rows returned using pg_stat_statements.rows (which includes the 1 row returned by the count query) and JVM heap allocation per request using ThreadMXBean.getCurrentThreadAllocatedBytes().

Posts / CommentsStrategyQueriesDB Rows ReadMedian LatencyHeap Allocated
1K / 10Kfetch join + paging210,00139.4ms11.8MB
100K / 1Mfetch join + paging21,000,0013,830.8ms1,174.6MB
100K / 1M@EntityGraph + paging21,000,0013,408.5ms1,174.6MB
100K / 1MID-first 2-step31116.1ms0.2MB
100K / 1MBatch fetch (100)31115.3ms0.1MB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
{
  "type": "line",
  "data": {
    "labels": ["10K comments", "100K comments", "500K comments", "1M comments"],
    "datasets": [
      { "label": "fetch join + paging", "data": [39.4, 300.8, 1646.9, 3830.8], "borderColor": "#f7768e" },
      { "label": "@EntityGraph + paging", "data": [35.6, 298.3, 1618.2, 3408.5], "borderColor": "#e0af68" },
      { "label": "ID-first 2-step", "data": [4.3, 3.8, 5.3, 6.1], "borderColor": "#7aa2f7" },
      { "label": "Batch fetch (100)", "data": [3.2, 3.1, 4.7, 5.3], "borderColor": "#9ece6a" }
    ]
  },
  "options": {
    "plugins": { "title": { "display": true, "text": "First-page (10 posts) median latency (ms, log scale)" } },
    "scales": { "y": { "type": "logarithmic", "title": { "display": true, "text": "ms" } } }
  }
}

With in-memory pagination, both latency and memory allocation scaled linearly with total table size. At 1 million comments, a single 10-post page allocated over 1.17GB of heap objects. Both alternatives stayed flat at 111 rows read (10 posts + 100 comments + 1 count row) even when the dataset grew 100x.

Constraining the JVM heap made the failure mode even clearer. On the 1M-comment dataset, fetch join + paging crashed with java.lang.OutOfMemoryError: Java heap space under -Xmx512m and needed -Xmx1g just to finish in 1.9 seconds. Meanwhile, ID-first paging and batch fetching ran cleanly under -Xmx256m in 12.3ms and 8.0ms respectively. If you want to trace why the full join dominates PostgreSQL execution time at the query planner level, you can walk through the plan using the steps in Reading PostgreSQL EXPLAIN ANALYZE execution plans.

Choosing an approach and takeaways

Use caseRecommended approachWhy
Paginated list needing full child collectionsBatch fetch (default_batch_fetch_size)Fixed 3 queries with minimal code changes
Paginated list filtering parents by child columnsID-first paging + in fetch joinFilter and page in the ID query, hydrate in step 2
Single-record detail viewCollection join fetchNo pagination involved, so no memory slicing
Paginated list needing only counts or summariesDTO projection + count subquerySkips entity hydration altogether

When not to use collection fetch joins is straightforward: never pair them with pagination, and never fetch two or more collections in the same query. Fetching two List collections throws MultipleBagFetchException, and switching them to Set avoids the exception only by producing a Cartesian product that multiplies rows exponentially. Batch fetching isn’t a silver bullet either—if your screen only needs a filtered subset of a child collection (such as the latest 3 comments per post), skip entity loading and use a dedicated DTO query instead.

Watch out for silent warnings in development: HHH90003004 is easy to miss when your local database has only a few thousand rows. In my 10K-comment test, the bad query still returned in 39ms and looked completely fine. It only turns into an OOM outage after production data grows. Enable hibernate.query.fail_on_pagination_over_collection_fetch: true in your dev and test profiles so CI catches it before merge.

  • Verify no paginated query uses a collection join fetch or collection @EntityGraph.
  • Search application logs for HHH90003004 warnings across existing endpoints.
  • Enable hibernate.query.fail_on_pagination_over_collection_fetch=true in test profiles.
  • Confirm list endpoints execute a fixed query count via default_batch_fetch_size or ID-first paging.
  • Provide an explicit countQuery so count queries don’t carry unnecessary joins.
This post is licensed under CC BY 4.0 by the author.