Hibernate: A stateless session for bulk work

No persistence context means no dirty checking, no cascade, and no memory growth over a million rows.

Code
StatelessSession session = sessionFactory.openStatelessSession();
Transaction tx = session.beginTransaction();

try (var rows = repo.streamAll()) {
    rows.forEach(session::insert);
}
tx.commit();
session.close();
Output
A normal session holds every entity until flush and eventually OOMs.
A stateless session holds none - but you lose cascading and lazy loading.
Advertisement

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-11