Video in progress
What is `StatelessSession` and when would you use it instead of a regular `Session`?
StatelessSession works without a persistence context: no snapshots, no dirty checking, no cascade, and no L1/L2 cache. Every insert/update turns into SQL right away, so memory stays steady and it's fast for big import and export jobs.
📖 Answer
You need to load 2 million rows from a big CSV. With a regular Session, every entity stays in the context, and if you forget flush/clear, memory keeps filling up. With StatelessSession there's no such worry:
try (StatelessSession ss = sessionFactory.openStatelessSession()) {
Transaction tx = ss.beginTransaction();
for (CsvRow row : rows) {
ss.insert(new Payment(row.id(), row.amount(), row.date()));
}
tx.commit();
}
On batching, check your version: in older versions a stateless session didn't do JDBC batching, while newer 6.x versions support batching, and Hibernate 7 added methods like insertMultiple().
What you give up:
- lazy loading doesn't work: if you touch an association, you get an exception;
- no cascade: you insert the parent and the child separately;
- changes aren't saved automatically, and you have to call
update(entity)explicitly; @Versionworks, but Hibernate's usual event listeners (audit, Envers) don't go through this path; and if you read an object twice, you get two different instances.
Spring Data repositories don't work with StatelessSession. You get it through EntityManagerFactory.unwrap(SessionFactory.class) and manage the transaction by hand (or use the Jakarta Data repositories in Hibernate 6.6+).
You don't need it for ordinary CRUD. Batch jobs, ETL and migration scripts are where it belongs.
Sign up to mark studied questions and save your progress.