Skip to content
Tutorials Center
My learning

Topics

Lesson 6 of 39 ยท Configuration and Sessions

SessionFactory and Session

Learn how Hibernate's SessionFactory and Session differ, why one is shared and the other is short-lived, session-per-request, closing sessions and the StatelessSession.

Two objects dominate everyday Hibernate use. The SessionFactory is the big, shared, thread-safe object created once. The Session is the small, short-lived, single-threaded object you open for each unit of work. Mixing up their lifetimes is the source of many classic bugs: a factory built on every request makes an application crawl, and a session shared between threads corrupts data.

This lesson explains both objects, the recommended lifecycle, and what the session is actually holding. Real Hibernate code is read-only; the runnable programs are stand-ins that demonstrate the lifetimes with plain Java.

SessionFactory: build once, share

Building a SessionFactory parses all mappings, builds metadata, validates the model, prepares caches and the connection pool. That takes seconds on a large model. So:

  • Create one per database when the application starts.
  • It is immutable and thread-safe; every thread may use it.
  • Close it when the application shuts down (sessionFactory.close()).
Java
public final class HibernateUtil {
    private static final SessionFactory SESSION_FACTORY = new Configuration()
            .configure()
            .buildSessionFactory();

    private HibernateUtil() {}

    public static SessionFactory sessionFactory() { return SESSION_FACTORY; }
}

In a framework (Spring, Quarkus, Jakarta EE) the container builds and injects it for you, and you never write a utility class like this.

Session: one unit of work

A Session is a lightweight wrapper around one JDBC connection (borrowed lazily from the pool) and a persistence context: the map of entities loaded or persisted through it. Create it, use it for a request or business operation, and close it.

Java
try (Session session = sessionFactory.openSession()) {
    Transaction tx = session.beginTransaction();
    try {
        Book book = session.find(Book.class, 1L);
        book.setTitle("Updated");
        tx.commit();
    } catch (RuntimeException e) {
        tx.rollback();
        throw e;
    }
}

The convenient helpers do all of that for you:

Java
sessionFactory.inTransaction(session -> {      // open, begin, run, commit/rollback, close
    session.find(Book.class, 1L).setTitle("Updated");
});

sessionFactory.inSession(session -> {          // open, run, close (no transaction)
    session.find(Book.class, 1L);
});

A Session is not thread-safe. Never store it in a static field, a singleton service or a shared cache, and never pass it to another thread. One thread, one session at a time.

Session-per-request

In a web application the standard pattern is one session per request (often per transaction): open at the start of handling a request, close at the end. Spring does this with @Transactional; Jakarta EE with a container-managed EntityManager. The rule of thumb:

flowchart LR
    A["Application starts"] --> B["Build SessionFactory (once)"]
    B --> C["Request 1: open Session"]
    B --> D["Request 2: open Session"]
    C --> E["Close Session"]
    D --> F["Close Session"]
    E --> G["Application stops: close SessionFactory"]
    F --> G

Many short sessions, one long-lived factory.

Avoid the opposite anti-pattern, session-per-application: one session for the whole program. It grows without bound (every entity ever loaded stays in memory), returns stale data and is not thread-safe.

What does a session hold?

  • A persistence context (the first-level cache): every managed entity, by type and ID.
  • A snapshot of each entity's loaded state, used for dirty checking.
  • A queue of pending actions (inserts, updates, deletes) waiting for a flush.
  • A lazily acquired JDBC connection and the current transaction.

That is why a long-lived session leaks memory, and why an exception can leave a session in an inconsistent state: after a Hibernate exception, discard the session. See Entity states and the persistence context and Flush and dirty checking.

Stand-in: expensive factory, cheap sessions

This program is a stand-in: a small factory that "builds metadata" once and hands out sessions that share it. It counts how often the expensive step runs, shows that each session has its own state, and shows that a closed session refuses further work, which is roughly how Hibernate behaves.

Java Stand-in: factory versus sessions

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Stand-in: why sessions are not shared between threads

A session holds mutable state and no locks. Two threads working in the same one can interleave their changes, so the rule is one session per thread. The stand-in below gives each worker thread its own "session" (a private list) and combines the results afterwards.

Java Stand-in: one session per thread

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

StatelessSession

Sometimes you want raw speed and no tracking at all: a bulk import, a data migration, a streaming export. A StatelessSession has no persistence context, no first-level cache, no dirty checking and no cascades; each call goes straight to the database.

Java
try (StatelessSession ss = sessionFactory.openStatelessSession()) {
    Transaction tx = ss.beginTransaction();
    for (Book b : hugeList) {
        ss.insert(b);                       // INSERT now, nothing is tracked
    }
    tx.commit();
}

The price: no automatic updates (you call update yourself) and no lazy loading. For ordinary business logic use the normal Session.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. How many SessionFactory instances does a typical application create per database?

    The factory is expensive and thread-safe, so build it once and share it.
  2. 2. Which statement about Session is true?

    A Session is a per-unit-of-work object that is not thread-safe.
  3. 3. What is wrong with one Session for the entire application?

    The persistence context keeps every loaded entity, so a long-lived session leaks memory and goes stale.
  4. 4. What does inTransaction do after your lambda finishes normally?

    It commits (rolling back on exceptions) and closes the session for you.
  5. 5. When is StatelessSession appropriate?

    It skips the persistence context, which suits bulk operations, but it gives up dirty checking and lazy loading.

Summary

  • SessionFactory: expensive, immutable, thread-safe, built once and closed at shutdown.
  • Session: cheap, mutable, not thread-safe; one per unit of work (session-per-request).
  • A session holds the persistence context, snapshots and pending actions, so close it promptly.
  • Use inTransaction / inSession or the framework's transaction management instead of manual open/close code.
  • StatelessSession trades tracking for speed in bulk work.

Next: Entity States and the Persistence Context