A StatelessSession
is a lighter, faster version of Session
.
It does not use first-level cache, doesn’t track entity states, or support automatic flushing.
Best suited for batch processing where you just want to read or write data efficiently without overhead.
🔹 Why use it?
✅ Avoids memory overhead from tracking entities.
✅ Reduces CPU time Hibernate spends on dirty checking.
✅ Excellent for ETL, data migration, or large-scale imports.
🔹 How to obtain a StatelessSession:
You open it directly from the SessionFactory
:
StatelessSession statelessSession = sessionFactory.openStatelessSession();
Transaction tx = statelessSession.beginTransaction();
🔹 Example: Bulk insert with StatelessSession
StatelessSession statelessSession = sessionFactory.openStatelessSession();
Transaction tx = statelessSession.beginTransaction();
for (int i = 0; i < 10000; i++) {
User user = new User();
user.setUsername("bulk_user_" + i);
user.setEmail("bulk" + i + "@example.com");
statelessSession.insert(user); // no caching, direct insert
}
tx.commit();
statelessSession.close();
✅ In this example:
- Hibernate skips first-level caching and change tracking, writing data directly to the database → much faster for big batches.
🔹 Important differences vs. regular Session:
Feature | Session | StatelessSession |
---|---|---|
Caching | Uses first-level | No first-level cache |
Dirty checking | Automatic | None — you must manage changes manually |
Associations | Fully supported | Limited, no automatic cascading |
Use case | General CRUD | Bulk operations |
✅ Key takeaway:
Use StatelessSession
when you need maximum performance for batch inserts or updates, but remember: you lose convenience features like caching, automatic flush, and change tracking.