OutOfMemoryError during in-memory pagination in Hibernate ORM
0 reputation · 11 Sept 2020, 17:11 UTC
When implementing pagination using setFirstResult() and setMaxResults() in Hibernate, the framework typically delegates the row limiting to the database via the configured Dialect.
However, a specific conflict occurs when pagination is combined with join fetches on collection-based relationships (such as OneToMany). In these scenarios, Hibernate may be unable to generate a SQL query that accurately limits the result set without duplicating parent entities, leading it to perform pagination in-memory after loading the entire dataset.
Given the risk of heap exhaustion on large datasets, what are the recommended architectural patterns to achieve true database-level pagination while still retrieving associated collections? Which alternative fetching strategies prevent the transition to in-memory processing?