Skip to content
Tutorials Center
My learning

Topics

Lesson 10 of 39 ยท Configuration and Sessions

Bootstrapping Hibernate in Code

Build a Hibernate SessionFactory in plain Java: StandardServiceRegistry, MetadataSources, Metadata, the bootstrap steps, and a runnable stand-in of the builder flow.

In the previous lessons a SessionFactory appeared almost by magic from hibernate.cfg.xml. Behind that one line, Hibernate runs a fixed sequence of steps. You can run the same steps yourself in Java, which is handy in tests, in frameworks that own the configuration, and when you want to know exactly what happens at start-up.

Real Hibernate code in this lesson is read-only; the runnable programs are plain-Java stand-ins that model the idea.

The three stages

Hibernate separates start-up into three stages, each with its own object:

  1. StandardServiceRegistry: the settings (JDBC URL, dialect, pool) and the services built from them (connection provider, transaction coordinator).
  2. Metadata: the parsed mapping model: which classes are entities, which columns they map to, which associations exist.
  3. SessionFactory: the immutable, thread-safe object you keep for the whole application.
flowchart LR
    S["Settings<br/>(properties, cfg.xml)"] --> R["StandardServiceRegistry"]
    C["Annotated classes"] --> M["MetadataSources"]
    R --> M
    M --> MD["Metadata"]
    MD --> SF["SessionFactory"]

Settings and annotated classes meet in MetadataSources, which produces the Metadata the factory is built from.

The code

Java
StandardServiceRegistry registry = new StandardServiceRegistryBuilder()
        .configure()                                  // reads hibernate.cfg.xml (optional)
        .applySetting("hibernate.show_sql", "true")   // overrides or adds a setting
        .build();

try {
    SessionFactory sessionFactory = new MetadataSources(registry)
            .addAnnotatedClass(Book.class)
            .addAnnotatedClass(Author.class)
            .buildMetadata()
            .buildSessionFactory();
    // use it for the whole application
} catch (Exception e) {
    StandardServiceRegistryBuilder.destroy(registry); // release services if start-up failed
    throw e;
}

Three details matter:

  • configure() is optional. Without it, you set everything with applySetting, applySettings(Map) or a hibernate.properties file on the classpath.
  • You own the registry. If building the factory fails, destroy the registry yourself, or pooled connections stay open.
  • Order of precedence: settings applied later in the builder win over earlier ones, so applySetting after configure() overrides the XML file.

There is a shorter way for the common case:

Java
SessionFactory sessionFactory = new Configuration()
        .addAnnotatedClass(Book.class)
        .setProperty("hibernate.connection.url", "jdbc:h2:mem:demo")
        .buildSessionFactory();

Configuration wraps the same registry-and-metadata steps. It is fine for small programs; use the explicit form when you need control over the registry.

Stand-in: a settings builder

The registry builder is an ordinary builder: collect settings, then build() a read-only object. This program models its precedence rule.

Java Stand-in: settings builder with precedence

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: building metadata from classes

MetadataSources takes class objects and turns their annotations into a mapping model. The stand-in does the same with our own tiny annotations and reflection.

Java Stand-in: MetadataSources with reflection

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.

A real Metadata object does much more: it resolves associations, checks that every mapping is consistent and fails fast with a MappingException when it is not. That is why start-up errors in Hibernate usually point at a mapping mistake, before any query runs.

When you bootstrap yourself

  • Unit and integration tests: build a factory against an in-memory database with create-drop (schema generation).
  • Several databases: one registry and one factory per data source.
  • Frameworks: Spring Boot, Quarkus and Jakarta EE containers do the bootstrapping for you; the settings you learned here appear as their configuration properties.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which object holds the JDBC settings and the services built from them?

    The StandardServiceRegistry is built from settings and provides services such as the connection provider.
  2. 2. What should you do if buildSessionFactory() throws during bootstrapping?

    You created the registry, so you must destroy it with StandardServiceRegistryBuilder.destroy to release its resources.
  3. 3. In the builder, configure() reads hibernate.cfg.xml and a later applySetting uses the same key. Which value wins?

    Settings applied later override earlier ones.
  4. 4. What does MetadataSources produce?

    buildMetadata() turns the registered classes into the mapping model used to build the SessionFactory.

Summary

  • Bootstrapping has three stages: registry (settings and services), metadata (mappings) and the SessionFactory.
  • StandardServiceRegistryBuilder plus MetadataSources is the explicit form; Configuration is the short form.
  • Later settings override earlier ones; destroy the registry if start-up fails.
  • The factory is built once; frameworks usually do this for you.
  • Here, real Hibernate code is read-only; the runnable programs are plain-Java stand-ins.

Next: Entity and Column Mapping