Hibernate: a batch loop without flush and clear runs the heap out

Every persist adds a managed entity, its snapshot and its collection state to the persistence context, and nothing leaves until the transaction ends. Inserting 100,000 rows in one transaction holds all 100,000 in memory.

Full code & output

This topic is available to PRO members.

Sign in Create a free account

Run this yourself in the Online Java Compiler, spin up a live REST API in the API Sandbox, or practise with Java interview questions.

Published 2026-08-25