Hibernate Configuration File (hibernate.cfg.xml)

In this tutorial, we will learn how to create and configure a Hibernate configuration file (hibernate.cfg.xml) by connecting to a MySQL database using the User entity.

Introduction

The hibernate.cfg.xml file is a central piece in Hibernate that allows you to define database connection settings, Hibernate properties, and mappings.

In this tutorial, we will:

  1. Set up a Maven project with necessary dependencies.
  2. Create an entity class (User).
  3. Create and configure the hibernate.cfg.xml file.
  4. Demonstrate loading the configuration and building the SessionFactory.

Step 1: Set Up Your Project

1.1 Create a Maven Project

Open your IDE and create a new Maven project.

1.2 Add Dependencies

Update your pom.xml file to include dependencies for Hibernate and MySQL.

<project xmlns="http://maven.apache.org/POM/4.0.0"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.example</groupId>
    <artifactId>hibernate-configuration-example</artifactId>
    <version>1.0-SNAPSHOT</version>

    <dependencies>
        <!-- Hibernate ORM -->
        <dependency>
            <groupId>org.hibernate.orm</groupId>
            <artifactId>hibernate-core</artifactId>
            <version>6.4.0.Final</version>
        </dependency>

        <!-- MySQL Connector -->
        <dependency>
            <groupId>com.mysql</groupId>
            <artifactId>mysql-connector-j</artifactId>
            <version>9.0.0</version>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.10.1</version>
                <configuration>
                    <source>21</source>
                    <target>21</target>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>

Step 2: Create the Entity Class

Create an entity class User that will be mapped to a table in the database. This class uses annotations to define the entity and its fields.

package com.example.entity;

import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;

@Entity
public class User {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String username;
    private String password;

    // Getters and setters
    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }
}

Explanation:

  • The @Entity annotation specifies that the class is an entity and is mapped to a database table.
  • The @Id annotation specifies the primary key of the entity.
  • The @GeneratedValue(strategy = GenerationType.IDENTITY) annotation specifies that the primary key is auto-incremented.

Step 3: Create and Configure hibernate.cfg.xml

Create a hibernate.cfg.xml file in the src/main/resources directory to configure database connection settings and Hibernate properties.

<!DOCTYPE hibernate-configuration PUBLIC
    "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
    "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">

<hibernate-configuration>
    <session-factory>
        <!-- JDBC Database connection settings -->
        <property name="hibernate.connection.driver_class">com.mysql.cj.jdbc.Driver</property>
        <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/hibernate_db</property>
        <property name="hibernate.connection.username">root</property>
        <property name="hibernate.connection.password">password</property>

        <!-- JDBC connection pool settings -->
        <property name="hibernate.c3p0.min_size">5</property>
        <property name="hibernate.c3p0.max_size">20</property>
        <property name="hibernate.c3p0.timeout">300</property>
        <property name="hibernate.c3p0.max_statements">50</property>
        <property name="hibernate.c3p0.idle_test_period">3000</property>

        <!-- SQL dialect -->
        <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>

        <!-- Echo all executed SQL to stdout -->
        <property name="hibernate.show_sql">true</property>
        <property name="hibernate.format_sql">true</property>

        <!-- Drop and re-create the database schema on startup -->
        <property name="hibernate.hbm2ddl.auto">update</property>

        <!-- Entities -->
        <mapping class="com.example.entity.User"/>
    </session-factory>
</hibernate-configuration>

Explanation:

  • hibernate.connection.driver_class specifies the JDBC driver class for MySQL.
  • hibernate.connection.url specifies the JDBC URL for the database connection.
  • hibernate.connection.username and hibernate.connection.password specify the database credentials.
  • hibernate.c3p0 properties configure the connection pool settings using C3P0.
  • hibernate.dialect specifies the SQL dialect to be used.
  • hibernate.show_sql and hibernate.format_sql properties are used to display and format the generated SQL statements.
  • hibernate.hbm2ddl.auto specifies the schema generation strategy.
  • The <mapping class="com.example.entity.User"/> line maps the User entity to the database.

Step 4: Demonstrate Loading the Configuration and Building the SessionFactory

Create a main class to demonstrate loading the configuration and building the SessionFactory.

4.1 Create HibernateUtil Class

Create a utility class HibernateUtil to manage the Hibernate SessionFactory.

package com.example.util;

import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

public class HibernateUtil {
    private static final SessionFactory sessionFactory = buildSessionFactory();

    private static SessionFactory buildSessionFactory() {
        try {
            // Load the configuration and build the SessionFactory
            return new Configuration().configure().buildSessionFactory();
        } catch (Throwable ex) {
            System.err.println("Initial SessionFactory creation failed." + ex);
            throw new ExceptionInInitializerError(ex);
        }
    }

    public static SessionFactory getSessionFactory() {
        return sessionFactory;
    }

    public static void shutdown() {
        getSessionFactory().close();
    }
}

Explanation:

  • The HibernateUtil class provides a singleton SessionFactory and a method to shut it down.
  • The buildSessionFactory method loads the Hibernate configuration from hibernate.cfg.xml and builds the SessionFactory.

How Hibernate Loads hibernate.cfg.xml

When you invoke new Configuration().configure(), Hibernate performs the following steps:

  1. Classpath Search: It searches the root of the classpath for a file named hibernate.cfg.xml. This means that the file should be placed in the src/main/resources directory (or equivalent, depending on your build tool). Once the file is found, it is automatically used to configure Hibernate.

  2. Configuration Parsing: If found, Hibernate parses the hibernate.cfg.xml file and uses the settings defined in the file (such as database connection properties, Hibernate dialect, and entity mappings) to initialize the SessionFactory.

Why You Don’t Explicitly Pass hibernate.cfg.xml:

Since Configuration().configure() assumes the default hibernate.cfg.xml in the classpath, there’s no need to explicitly pass the file’s path unless it's located elsewhere or has a different name. If it's named something else or placed in a non-standard location, you can pass the file path explicitly like this:

return new Configuration().configure("path/to/your/config/file.xml").buildSessionFactory();

Key Points:

  1. Default Location: By default, hibernate.cfg.xml should be in the src/main/resources directory.
  2. Default Behavior: The new Configuration().configure() method looks for hibernate.cfg.xml on the classpath.
  3. Explicit Path: If the file is named differently or located elsewhere, use new Configuration().configure("your-custom-config.xml").

If the file is properly placed in resources, Hibernate will automatically load it when the SessionFactory is initialized. Let me know if you need more clarification!

4.2 Create MainApp

package com.example.main;

import com.example.util.HibernateUtil;
import org.hibernate.Session;
import org.hibernate.SessionFactory;

public class MainApp {
    public static void main(String[] args) {
        // Load the configuration and build the SessionFactory
        SessionFactory sessionFactory = HibernateUtil.getSessionFactory();

        // Open a new session
        Session session = sessionFactory.openSession();

        // Close the session
        session.close();

        // Shut down the SessionFactory
        HibernateUtil.shutdown();
    }
}

Explanation:

  • The getSessionFactory method of HibernateUtil is called to obtain the SessionFactory.
  • A new session is opened and closed to demonstrate the basic usage.
  • The shutdown method of HibernateUtil is called to close the SessionFactory and release resources.

Step 5: Run the Application

  1. Ensure your MySQL database is running and the connection details in hibernate.cfg.xml are correct.
  2. Run the MainApp class to load the Hibernate configuration, build the SessionFactory, open and close a session, and shut down the SessionFactory.

Output:

If everything is set up correctly, running the MainApp class should not produce any errors, and you should see the generated SQL statements in the console output, indicating that the configuration was loaded successfully.

Conclusion

In this tutorial, we have successfully demonstrated how to create and configure a Hibernate configuration file (hibernate.cfg.xml) to connect to a MySQL database using the User entity. We configured the project dependencies, created an entity class, set up the Hibernate configuration file, and demonstrated loading the configuration and building the SessionFactory. This guide provides a solid foundation for using Hibernate with a MySQL database in your applications.

Comments