Skip to content
Tutorials Center
My learning

Topics

Lesson 5 of 39 ยท Configuration and Sessions

Hibernate Configuration

Configure Hibernate with hibernate.cfg.xml, persistence.xml, properties and code. Learn the key settings, connection pooling, batching and how to log SQL and bind parameters.

Hibernate is configured with settings: name-value pairs such as hibernate.connection.url or hibernate.jdbc.batch_size. Where those settings come from is up to you. They can live in hibernate.cfg.xml, in persistence.xml, in a hibernate.properties file, in system properties, or be set in code. The result is always the same: one SessionFactory built from a merged set of settings and a list of mapped classes.

This lesson covers the configuration sources, the settings that matter most in practice, connection pooling, and how to see the SQL. The Hibernate code and XML are read-only here; the runnable programs are stand-ins that demonstrate the ideas (settings precedence and pooling) with plain Java.

Where settings come from

Source Typical use
hibernate.cfg.xml Native Hibernate bootstrap (new Configuration().configure())
META-INF/persistence.xml Standard JPA bootstrap (Persistence.createEntityManagerFactory("unit"))
hibernate.properties Simple key/value file read automatically from the classpath root
System properties (-Dhibernate.show_sql=true) Per-run overrides
Code (Configuration.setProperty, builders) Tests and frameworks
Spring Boot application.properties spring.jpa.properties.hibernate.* passes settings through

Settings you set in code usually override the file. A typical bootstrap in code:

Java
Configuration cfg = new Configuration()
        .configure()                                   // reads hibernate.cfg.xml
        .setProperty("hibernate.show_sql", "true")     // overrides / adds
        .addAnnotatedClass(Book.class)
        .addAnnotatedClass(Author.class);

SessionFactory sessionFactory = cfg.buildSessionFactory();

And the lower-level, fully programmatic form, which is what frameworks use:

Java
StandardServiceRegistry registry = new StandardServiceRegistryBuilder()
        .applySetting("hibernate.connection.url", "jdbc:postgresql://localhost/shop")
        .applySetting("hibernate.connection.username", "shop")
        .build();

SessionFactory sessionFactory = new MetadataSources(registry)
        .addAnnotatedClass(Book.class)
        .buildMetadata()
        .buildSessionFactory();

The settings you will actually use

XML
<!-- Connection (use a real pool in production, see below) -->
<property name="hibernate.connection.url">jdbc:postgresql://localhost/shop</property>
<property name="hibernate.connection.username">shop</property>
<property name="hibernate.connection.password">secret</property>

<!-- Dialect: normally detected from the connection; set it only when you must -->
<!-- <property name="hibernate.dialect">org.hibernate.dialect.PostgreSQLDialect</property> -->

<!-- SQL visibility -->
<property name="hibernate.show_sql">true</property>
<property name="hibernate.format_sql">true</property>
<property name="hibernate.highlight_sql">true</property>

<!-- Schema tooling (see the schema lesson) -->
<property name="hibernate.hbm2ddl.auto">validate</property>

<!-- Batching -->
<property name="hibernate.jdbc.batch_size">50</property>
<property name="hibernate.order_inserts">true</property>
<property name="hibernate.order_updates">true</property>

<!-- Misc -->
<property name="hibernate.default_schema">public</property>
<property name="hibernate.jdbc.time_zone">UTC</property>
  • hibernate.dialect is detected automatically in modern versions, so remove explicit dialects unless the database cannot be detected (or you need to pin a version).
  • jdbc.batch_size makes Hibernate group many inserts or updates into one JDBC batch, which can be a large speed-up (more in Caching and performance).
  • jdbc.time_zone=UTC stores timestamps in one zone and avoids many "off by one hour" bugs.

Logging SQL properly

show_sql prints statements to the console, which is fine for a quick look but bypasses your logging framework. The better way is to enable the loggers, so output follows your log format and levels:

XML
<!-- log4j2 / logback logger names -->
<Logger name="org.hibernate.SQL" level="debug"/>
<Logger name="org.hibernate.orm.jdbc.bind" level="trace"/>   <!-- bound parameter values -->

org.hibernate.SQL prints each statement with ? placeholders; org.hibernate.orm.jdbc.bind prints the values bound to them. Turn the second on only while debugging, because parameters can contain sensitive data.

Never leave bind-parameter logging on in production. Passwords, tokens and personal data would end up in your log files.

Connection pooling

Opening a database connection is slow. Hibernate's built-in pool is a minimal one and is meant for tests. In production, use a proper pool such as HikariCP, configured either through the hibernate-hikaricp module or by passing a DataSource (Spring Boot does this for you):

XML
<property name="hibernate.hikari.maximumPoolSize">10</property>
<property name="hibernate.hikari.minimumIdle">2</property>
<property name="hibernate.hikari.idleTimeout">300000</property>

A pool keeps a fixed set of open connections and lends them out for a single unit of work. The size should be modest: many databases perform worse with hundreds of concurrent connections than with a few dozen. The stand-in below is a small pool built on a BlockingQueue. It shows the key behavior: connections are opened once and then reused.

Java Stand-in: a tiny connection pool

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: how settings merge

When the same setting is defined in several places, one wins. A sensible rule, and the one most setups follow, is: defaults < file < system properties < code. This stand-in implements that merge so you can see why a -D flag changes behavior without editing the file.

Java Stand-in: settings 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.

Practical checklist

  • Keep credentials out of the file: use environment variables, a secret store or Spring/Quarkus placeholders.
  • Use one configuration approach per application; mixing hibernate.cfg.xml and persistence.xml causes confusion.
  • Set hbm2ddl.auto to none or validate outside local development (Schema generation).
  • Use a real connection pool and size it deliberately.
  • Switch on org.hibernate.SQL logging in development and keep an eye on the statement count.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which file is the standard JPA configuration file?

    persistence.xml defines persistence units for standard JPA bootstrap; hibernate.cfg.xml is Hibernate's native format.
  2. 2. Which logger prints the values bound to SQL parameters?

    org.hibernate.SQL shows statements; org.hibernate.orm.jdbc.bind at trace level shows the bound values.
  3. 3. Why use a pool like HikariCP instead of Hibernate's built-in pool?

    Hibernate's built-in pool is deliberately simple; production systems should use a robust pool.
  4. 4. A setting defined in both the file and in code. Which usually wins?

    Values set programmatically are applied on top of those read from files.
  5. 5. Why should bind-parameter logging stay off in production?

    Bound parameters can hold passwords, tokens and personal data.

Summary

  • Settings can come from hibernate.cfg.xml, persistence.xml, properties, system properties or code, merged into one set.
  • Key settings: connection, dialect (usually auto-detected), SQL logging, hbm2ddl.auto, batching and time zone.
  • Log SQL through the org.hibernate.SQL logger; turn on bind logging only while debugging.
  • Use a production connection pool (HikariCP) and size it sensibly.

Next: SessionFactory and Session