Hibernate Configuration
Configure Hibernate using hibernate.cfg.xml, covering connection settings, SQL dialect, and mapping registration.
Introduction
Hibernate needs to know how to connect to your database, which SQL "dialect" to speak, and which classes to treat as entities. This lesson covers the classic XML-based configuration approach using hibernate.cfg.xml, which remains widely used and is the clearest way to see every setting explicitly.
- The two common ways to configure Hibernate.
- How to write a complete hibernate.cfg.xml file.
- What connection properties Hibernate requires.
- What a SQL dialect is and why it matters.
- How to register entity mappings in configuration.
Two Ways to Configure Hibernate
Hibernate supports configuring itself through an XML file (hibernate.cfg.xml) or through a plain Java Properties object (or a properties file). Both approaches set the exact same underlying settings — the choice is purely about style and tooling preference.
| Approach | File | Notes |
|---|---|---|
| XML-based | hibernate.cfg.xml | Most common in standalone Hibernate projects; explicit and easy to read. |
| Properties-based | hibernate.properties or a Properties object | Common when configuration is built programmatically or merged with other config. |
This lesson focuses on hibernate.cfg.xml since it is the most widely used in standalone Hibernate projects, and it is what the Configuration.configure() call from the previous lesson expects by default.
hibernate.cfg.xml Explained
Here is a complete, minimal hibernate.cfg.xml targeting a local MySQL database. Each setting is explained in the sections below.
<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd"><hibernate-configuration> <session-factory>
<!-- Connection settings --> <property name="hibernate.connection.driver_class">com.mysql.cj.jdbc.Driver</property> <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/school_db</property> <property name="hibernate.connection.username">root</property> <property name="hibernate.connection.password">password</property>
<!-- SQL dialect --> <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<!-- Optional but useful during development --> <property name="hibernate.show_sql">true</property> <property name="hibernate.format_sql">true</property> <property name="hibernate.hbm2ddl.auto">update</property>
<!-- Entity mappings --> <mapping class="com.programinds.Student"/>
</session-factory></hibernate-configuration>Connection Settings
The four connection properties tell Hibernate exactly how to reach your database, using the JDBC driver added in the previous lesson.
| Property | Purpose |
|---|---|
| hibernate.connection.driver_class | The fully qualified JDBC driver class to load. |
| hibernate.connection.url | The JDBC connection URL, including host, port, and database name. |
| hibernate.connection.username | The database username to authenticate with. |
| hibernate.connection.password | The database password to authenticate with. |
The SQL Dialect
Different databases speak slightly different flavors of SQL — MySQL, PostgreSQL, and Oracle each have their own quirks for things like pagination, auto-increment syntax, and data types. Hibernate's "dialect" setting tells it exactly which flavor of SQL to generate.
<!-- MySQL --><property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<!-- PostgreSQL --><property name="hibernate.dialect">org.hibernate.dialect.PostgreSQLDialect</property>
<!-- H2 (in-memory, common for testing) --><property name="hibernate.dialect">org.hibernate.dialect.H2Dialect</property>As of Hibernate 6, dialect is often auto-detected from the JDBC connection metadata, so explicitly setting hibernate.dialect is optional in many cases — but setting it explicitly remains a common, clear practice and avoids surprises.
Registering Mappings
Hibernate needs to know which classes are entities. Inside hibernate.cfg.xml, each entity class is registered with a <mapping> element.
<mapping class="com.programinds.Student"/><mapping class="com.programinds.Course"/><mapping class="com.programinds.Enrollment"/>Alternatively, as shown in the earlier lesson, entity classes can be registered programmatically with configuration.addAnnotatedClass(Student.class) instead of listing them in XML — both approaches achieve the same result.
Loading the Configuration
Once hibernate.cfg.xml exists on the classpath, loading it and building a SessionFactory is a single call.
import org.hibernate.SessionFactory;import org.hibernate.cfg.Configuration;
public class HibernateUtil {
private static final SessionFactory sessionFactory = new Configuration().configure("hibernate.cfg.xml").buildSessionFactory();
public static SessionFactory getSessionFactory() { return sessionFactory; }}Click Run to see what this code prints.
Common Mistakes
- Setting hibernate.hbm2ddl.auto to "update" (or worse, "create") in a production environment — it can silently alter your schema.
- Hardcoding real database passwords directly in hibernate.cfg.xml committed to version control.
- Mismatching the dialect and the actual database in use, causing subtly wrong generated SQL.
- Forgetting to register a new entity class after creating it, leading to "unknown entity" errors.
Best Practices
- Use hibernate.hbm2ddl.auto=validate or manage schema changes with a migration tool in production, reserving update for local development only.
- Keep credentials out of version control — use environment variables or a secrets manager for real projects.
- Enable hibernate.show_sql and hibernate.format_sql during development to see exactly what Hibernate generates.
- Set the dialect explicitly even when auto-detection works, for clarity and to catch mismatches early.
Frequently Asked Questions
It controls whether Hibernate automatically creates, updates, or validates your database schema based on your entity mappings. Common values are none, validate, update, create, and create-drop.
XML configuration for hibernate.cfg.xml is about connection and session-level settings, separate from entity mapping annotations like @Entity — most modern projects use annotations for entities and either XML or properties for connection settings.
In src/main/resources, so it is automatically included on the classpath and found by Configuration.configure().
In Hibernate 6, it is often auto-detected, but specifying it explicitly is still common practice and prevents ambiguity.
Key Takeaways
- hibernate.cfg.xml (or an equivalent properties file) tells Hibernate how to connect and behave.
- Connection settings, the dialect, and entity mappings are the three essential pieces.
- hibernate.hbm2ddl.auto controls automatic schema generation and should be used carefully.
- show_sql and format_sql are invaluable during development for seeing generated SQL.
Summary
With a complete hibernate.cfg.xml in place, Hibernate now knows how to connect to your database and speak the correct SQL dialect. Next, you will look more closely at SessionFactory and Session — why one is expensive and app-wide, while the other is cheap and short-lived.