Hibernate / Hibernate 7 Basics Interview Questions
What is the StatelessSession in Hibernate 7 and when should you use it?
StatelessSession has no first-level cache, no dirty checking, and no automatic state management. In Hibernate 7 it reaches near feature-parity with Session and is the preferred tool for bulk processing.
| Aspect | Session | StatelessSession |
|---|---|---|
| First-level cache | Yes | No |
| Dirty checking | Yes | No - must call update() explicitly |
| Memory | Can grow with large result sets | Minimal |
| L2 cache (Hibernate 7) | Yes | Yes (new - was bypassed in v6) |
| Best for | Transactional CRUD | Bulk ETL, batch imports, reporting |
try (StatelessSession ss = sf.openStatelessSession()) { ss.beginTransaction(); // Hibernate 7: must set batch size explicitly on StatelessSession! ss.setJdbcBatchSize(50); // hibernate.jdbc.batch_size has NO effect here // New batch operations in Hibernate 7: ss.insertMultiple(products); // batch inserts ss.updateMultiple(toUpdate); // batch updates // Bypass L2 cache for bulk operations (new default is to use it): ss.setCacheMode(CacheMode.IGNORE); // Scrollable results for very large datasets: ScrollableResults<Product> scroll = ss .createQuery("FROM Product", Product.class) .scroll(ScrollMode.FORWARD_ONLY); while (scroll.next()) { Product p = scroll.get(); p.setPrice(p.getPrice().multiply(new BigDecimal("0.9"))); ss.update(p); // explicit - no dirty checking } ss.getTransaction().commit(); }
More Related questions...