How do I configure hibernate.cfg.xml for a simple application?

To configure hibernate.cfg.xml for a simple Hibernate application, you need to include the essential properties for Hibernate to interact with the database and map your entities.

Below is an example of hibernate.cfg.xml:

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

<hibernate-configuration>
    <session-factory>

        <!-- Database connection settings -->
        <property name="hibernate.connection.driver_class">org.h2.Driver</property>
        <property name="hibernate.connection.url">jdbc:h2:mem:testdb</property>
        <property name="hibernate.connection.username">sa</property>
        <property name="hibernate.connection.password"></property>

        <!-- Hibernate dialect -->
        <property name="hibernate.dialect">org.hibernate.dialect.H2Dialect</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>

        <!-- Enable Hibernate's automatic table creation -->
        <property name="hibernate.hbm2ddl.auto">update</property>

        <!-- Show SQL logs in the console -->
        <property name="hibernate.show_sql">true</property>
        <property name="hibernate.format_sql">true</property>

        <!-- Add entity mappings -->
        <mapping class="org.kodejava.hibernate.Student"/>

    </session-factory>
</hibernate-configuration>

Explanation of the Configuration

  1. Database Connection Settings:
    • hibernate.connection.driver_class: Specifies the JDBC driver class (e.g., org.h2.Driver for an H2 database, com.mysql.cj.jdbc.Driver for MySQL, etc.).
    • hibernate.connection.url: JDBC URL to connect to your database.
    • hibernate.connection.username and hibernate.connection.password: Database credentials.
  2. Dialect:
    • hibernate.dialect: Hibernate’s SQL dialect for the specific database (e.g., H2Dialect, MySQLDialect, PostgreSQLDialect, etc.).
  3. Connection Pool:
    • Configures a simple C3P0 connection pool with properties like min_size, max_size, and timeout.
  4. Schema Management:
    • hibernate.hbm2ddl.auto:
      • create: Creates the schema, destroying any existing data.
      • update: Updates the schema, keeping existing data.
      • validate: Validates the schema without making changes.
      • none: Disables automatic schema management.
  5. SQL Output:
    • hibernate.show_sql: Logs executed SQL statements to the console.
    • hibernate.format_sql: Formats SQL logs for better readability.
  6. Entity Mapping:
    • <mapping class="org.kodejava.hibernate.Student"/>: Maps the Student entity to the database.

Using this Configuration

Place the hibernate.cfg.xml file in the src/main/resources directory (or in the root of your classpath). You can then use it to build a SessionFactory in your application:

SessionFactory factory = new Configuration()
        .configure("hibernate.cfg.xml")  // Load the config file
        .addAnnotatedClass(Student.class)  // Add annotated entity classes
        .buildSessionFactory();

This will allow Hibernate to connect to the database and manage your entities as per the configuration specified.

How do I set up Hibernate in a Maven project?

1. Introduction

In this post, we’ll walk through the process of setting up a basic Hibernate project using Maven. Hibernate is a powerful ORM (Object-Relational Mapping) tool for Java, and it’s often used to simplify database interactions in enterprise applications.

2. Prerequisites

  • Java JDK 17 or later
  • Maven installed
  • A code editor (e.g., IntelliJ IDEA, Eclipse)
  • A basic understanding of Java classes and interfaces

3. Create a Maven Project

If you’re using a terminal:

mvn archetype:generate -DgroupId=org.kodejava.hibernate \
    -DartifactId=hibernate-setup \
    -DarchetypeArtifactId=maven-archetype-quickstart \
    -DinteractiveMode=false

Navigate to the project folder:

cd hibernate-setup

4. Add Hibernate Dependencies

Edit your pom.xml to include the Hibernate Core dependency and H2 Database (for testing):

<dependencies>
    <!-- Hibernate Core -->
    <dependency>
        <groupId>org.hibernate.orm</groupId>
        <artifactId>hibernate-core</artifactId>
        <version>6.4.4.Final</version>
    </dependency>
    <!-- H2 Database -->
    <dependency>
        <groupId>com.h2database</groupId>
        <artifactId>h2</artifactId>
        <version>2.2.224</version>
        <scope>runtime</scope>
    </dependency>
    <dependency>
        <groupId>jakarta.persistence</groupId>
        <artifactId>jakarta.persistence-api</artifactId>
        <version>3.1.0</version>
    </dependency>
</dependencies>

5. Create Hibernate Configuration

Create a file named hibernate.cfg.xml under src/main/resources:

<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
        "-//Hibernate/Hibernate Configuration DTD//EN"
        "http://hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
    <session-factory>
        <!-- Database connection properties -->
        <property name="hibernate.connection.driver_class">org.h2.Driver</property>
        <property name="hibernate.connection.url">jdbc:h2:mem:testdb</property>
        <property name="hibernate.connection.username">sa</property>
        <property name="hibernate.connection.password"></property>

        <!-- Hibernate properties -->
        <property name="hibernate.dialect">org.hibernate.dialect.H2Dialect</property>
        <property name="hibernate.show_sql">true</property>
        <property name="hibernate.format_sql">true</property>

        <!-- Manage schema updates automatically -->
        <property name="hibernate.hbm2ddl.auto">update</property>

        <!-- Specify annotated entity classes -->
        <mapping class="org.kodejava.hibernate.Student" />
    </session-factory>
</hibernate-configuration>

6. Define a Simple Entity Class

package org.kodejava.hibernate;

import jakarta.persistence.*;

@Entity
@Table(name = "students")
public class Student {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    private String name;

    public Student() {}
    public Student(String name) { this.name = name; }

    // getters and setters
}

7. Write a Main Class to Test Hibernate

package org.kodejava.hibernate;

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

public class HibernateMain {
    public static void main(String[] args) {
        SessionFactory factory = new Configuration()
                .configure("hibernate.cfg.xml")
                .addAnnotatedClass(Student.class)
                .buildSessionFactory();

        Session session = factory.openSession();

        try {
            Student student = new Student("Alice");
            session.beginTransaction();
            session.persist(student);
            session.getTransaction().commit();
            System.out.println("Student saved successfully!");
        } finally {
            session.close();
            factory.close();
        }
    }
}

8. Run the Program

Compile and run the application:

mvn compile exec:java -Dexec.mainClass="org.kodejava.hibernate.HibernateMain"

9. Summary

You’ve now set up a basic Hibernate project using Maven and saved a simple entity to an in-memory database. In future posts, we’ll expand on this by adding relationships, custom queries, and performance tuning techniques.

How do I create Hibernate’s SessionFactory?

When creating an application the use Hibernate to manage our application persistence object we’ll need a SessionFactory. This factory creates or open a session to talk to a database.

To create a SessionFactory we can define the configuration in hibernate.properties, hibernate.cfg.xml or create it programmatically. In this example we’ll use the hibernate.cfg.xml configuration file, which is mostly use when creating Hibernate application.

Below is our session configuration files.

<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE hibernate-configuration PUBLIC
    "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
    "http://hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
    <session-factory>
        <!-- JDBC connection settings -->
        <property name="connection.driver_class">com.mysql.cj.jdbc.Driver</property>
        <property name="connection.url">jdbc:mysql://localhost/musicdb</property>
        <property name="connection.username">root</property>
        <property name="connection.password" />

        <!-- JDBC connection pool, use Hibernate internal connection pool -->
        <property name="connection.pool_size">5</property>

        <!-- Defines the SQL dialect used in Hibernate's application -->
        <property name="dialect">org.hibernate.dialect.MySQL8Dialect</property>

        <!-- Enable Hibernate's automatic session context management -->
        <property name="current_session_context_class">thread</property>

        <!-- Disable the second-level cache  -->
        <property name="cache.provider_class">org.hibernate.cache.internal.NoCachingRegionFactory</property>

        <!-- Display and format all executed SQL to stdout -->
        <property name="show_sql">true</property>
        <property name="format_sql">true</property>

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

        <!-- Mapping to hibernate mapping files -->
        <mapping resource="org/kodejava/hibernate/mapping/Label.hbm.xml"/>
    </session-factory>
</hibernate-configuration>

Now we have the configuration file done, let’s create a helper class that will configure and build the SessionFactory object. This helper will be used in other Hibernate example in this site.

package org.kodejava.hibernate;

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

public class SessionFactoryHelper {
    private static final SessionFactory sessionFactory;

    static {
        try {
            // Build a SessionFactory object from session-factory config
            // defined in the hibernate.cfg.xml file. In this file we
            // register the JDBC connection information, connection pool,
            // hibernate dialect that we used and the mapping to our
            // hbm.xml file for each pojo (plain old java object).
            Configuration config = new Configuration();
            sessionFactory = config.configure().buildSessionFactory();
        } catch (Throwable e) {
            System.err.println("Error in creating SessionFactory object."
                    + e.getMessage());
            throw new ExceptionInInitializerError(e);
        }
    }

    public static void main(String[] args) {
        Session session = SessionFactoryHelper.getSessionFactory()
                .getCurrentSession();
        System.out.println("session = " + session);
    }

    /**
     * A static method for other application to get SessionFactory object
     * initialized in this helper class.
     */
    public static SessionFactory getSessionFactory() {
        return sessionFactory;
    }
}

Maven Dependencies

<dependencies>
    <dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate-core</artifactId>
        <version>5.6.9.Final</version>
    </dependency>
    <dependency>
        <groupId>com.mysql</groupId>
        <artifactId>mysql-connector-j</artifactId>
        <version>8.0.33</version>
    </dependency>
</dependencies>

Maven Central Maven Central