Java.Hibernate.Beginner.Whats is Stateless session ?

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:

FeatureSessionStatelessSession
CachingUses first-levelNo first-level cache
Dirty checkingAutomaticNone — you must manage changes manually
AssociationsFully supportedLimited, no automatic cascading
Use caseGeneral CRUDBulk 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.

This entry was posted in Без рубрики. Bookmark the permalink.