LearnAI ToolsCareerPractice BuildsPlayContact
Lesson 420 min read

Hibernate Architecture Overview

Understand how Configuration, SessionFactory, Session, and Transaction fit together in Hibernate's core architecture.

Introduction

Before writing more Hibernate code, it helps to understand the four core objects you will interact with in nearly every Hibernate application: Configuration, SessionFactory, Session, and Transaction. This lesson maps out how they relate, so later lessons build on a clear mental model instead of memorized syntax.

What You Will Learn
  • The role of Configuration in setting up Hibernate.
  • Why SessionFactory is expensive to create and shared app-wide.
  • How Session represents a single unit of work.
  • How Transaction wraps operations to keep data consistent.
  • How all four pieces fit together in a real flow.

The Core Building Blocks

Hibernate's architecture can feel abstract until you see the four pieces laid out together. Each one has a distinct job and a distinct lifetime.

ComponentRoleTypical Lifetime
ConfigurationReads settings (DB connection, dialect, mappings) and bootstraps Hibernate.Used once, at startup.
SessionFactoryA heavyweight, thread-safe factory that produces Sessions.One per application (or per database).
SessionA lightweight, single-threaded unit of work for talking to the database.One per business operation or request.
TransactionGroups one or more operations so they succeed or fail together.One per Session, typically.

Configuration

Configuration is the starting point. It reads your settings — database URL, username, password, SQL dialect, and which entity classes to map — and uses them to build a SessionFactory.

Building a SessionFactory from Configuration
Configuration configuration = new Configuration();
configuration.configure("hibernate.cfg.xml");
configuration.addAnnotatedClass(Student.class);
SessionFactory sessionFactory = configuration.buildSessionFactory();

You will see the exact contents of hibernate.cfg.xml in the upcoming configuration lesson. For now, the key idea is: Configuration reads settings once, and its only real job is producing a SessionFactory.

SessionFactory

SessionFactory is deliberately expensive to create — it parses your mappings, builds internal metadata, and prepares connection pooling. Because of that cost, you create exactly one SessionFactory per application (or per database, if your app talks to more than one), and reuse it for the entire lifetime of the application.

Important

Never create a new SessionFactory for every request or operation. It is thread-safe and meant to be shared across your whole application — creating it repeatedly wastes significant time and resources.

Typical SessionFactory usage pattern
public class HibernateUtil {
private static final SessionFactory sessionFactory = buildSessionFactory();
private static SessionFactory buildSessionFactory() {
return new Configuration()
.configure("hibernate.cfg.xml")
.addAnnotatedClass(Student.class)
.buildSessionFactory();
}
public static SessionFactory getSessionFactory() {
return sessionFactory;
}
}

Session

Session, in contrast, is lightweight and cheap to create. It represents a single unit of work — typically one request, one method call, or one business operation. You open a Session, do your database work, and close it.

Opening and closing a Session
Session session = sessionFactory.openSession();
try {
// work with the session here
} finally {
session.close();
}
Mental Model

Think of SessionFactory like a database connection pool manager (create once, reuse forever) and Session like an individual borrowed connection (open, use briefly, close).

A Session is not thread-safe — each thread or request should get its own Session, never share one Session across multiple threads.

Transaction

A Transaction groups one or more database operations so that they either all succeed together or all fail together — preserving data consistency. In Hibernate, a Transaction is obtained from a Session and must be explicitly committed (or rolled back on error).

Using a Transaction
Session session = sessionFactory.openSession();
Transaction transaction = null;
try {
transaction = session.beginTransaction();
Student student = new Student();
student.setId(1L);
student.setName("Alex");
session.persist(student);
transaction.commit();
} catch (Exception e) {
if (transaction != null) {
transaction.rollback();
}
throw e;
} finally {
session.close();
}
Generated SQL on commit()

Click Run to see what this code prints.

Putting It All Together

A single, complete flow through all four components looks like this: Configuration reads your settings once and builds one SessionFactory. The SessionFactory then produces many Sessions over the application's lifetime — one per unit of work. Each Session opens a Transaction to safely group its database operations, then commits or rolls back before the Session closes.

  • 1. Configuration reads hibernate.cfg.xml and entity mappings.
  • 2. Configuration builds one SessionFactory (kept alive for the whole app).
  • 3. SessionFactory opens a new Session for each unit of work.
  • 4. Session begins a Transaction before making changes.
  • 5. Transaction commits (or rolls back), then the Session closes.

Common Mistakes

Avoid These Mistakes
  • Creating a new SessionFactory for every operation instead of once per application.
  • Sharing a single Session across multiple threads — Sessions are not thread-safe.
  • Forgetting to begin or commit a Transaction, leaving changes unsaved or partially applied.
  • Never closing a Session, leading to resource leaks over time.

Best Practices

  • Build exactly one SessionFactory per application and store it in a utility class or dependency-injection container.
  • Open a fresh Session for each unit of work and close it promptly (try-with-resources or try/finally).
  • Always wrap write operations in an explicit Transaction, with rollback on error.
  • Keep Session usage confined to a single thread.

Frequently Asked Questions

Typically one, shared and reused for the application's entire lifetime. Creating multiple is only needed when connecting to multiple, distinct databases.

No, a Session should be short-lived, generally scoped to a single request or unit of work, and is not safe to share across threads.

Your changes will not be persisted to the database — they exist only in memory within that Session until committed.

Hibernate generally recommends wrapping even read operations in a transaction for consistency, though some simple reads can work without one depending on configuration.

Key Takeaways

  • Configuration reads settings and builds a SessionFactory.
  • SessionFactory is expensive to create and should be built once per application.
  • Session is lightweight, represents one unit of work, and is not thread-safe.
  • Transaction groups operations so they succeed or fail together.

Summary

Configuration, SessionFactory, Session, and Transaction form the backbone of every Hibernate application. With this mental model in place, the next lesson walks through actually setting up a Hibernate project, starting with the Maven dependency and a JDBC driver.

Next Lesson →

Setting Up Hibernate