How Do I Set Up Hibernate ORM 7 in a Maven Project?

In article 1, we introduced a Book entity and showed what Hibernate does when you persist an object. Now we will create a complete Maven application that saves that book to H2 and loads it again through Jakarta Persistence.

We will keep the same package, title, and manually assigned identifier. Author and Publisher relationships will come later in the roadmap; this article establishes the runnable project they will use.

1. Prepare Java and Maven

Install JDK 25 and Maven 3.9 or later. Check that Maven uses JDK 25:

java -version
mvn -version

This example uses Hibernate ORM 7.4.17.Final, released November 19, 2026, the latest stable release verified on November 23, 2026. It updates Week 01’s 7.4.15.Final within the same release series. The official compatibility matrix lists Java 25 and Jakarta Persistence 3.2. H2 2.5.252 is listed on the official H2 download page.

2. Create the Maven project

Create a directory named hibernate-book-catalog. Inside it, create the files below. Paths are relative to this directory.

File: pom.xml

<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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>org.kodejava</groupId>
    <artifactId>hibernate-book-catalog</artifactId>
    <version>1.0-SNAPSHOT</version>

    <properties>
        <maven.compiler.release>25</maven.compiler.release>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.hibernate.orm</groupId>
            <artifactId>hibernate-core</artifactId>
            <version>7.4.17.Final</version>
        </dependency>
        <dependency>
            <groupId>com.h2database</groupId>
            <artifactId>h2</artifactId>
            <version>2.5.252</version>
            <scope>runtime</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.14.1</version>
            </plugin>
            <plugin>
                <groupId>org.codehaus.mojo</groupId>
                <artifactId>exec-maven-plugin</artifactId>
                <version>3.6.3</version>
                <configuration>
                    <mainClass>org.kodejava.hibernate.BookCatalogApp</mainClass>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>

Hibernate Core supplies the ORM implementation and brings in Jakarta Persistence transitively. H2 supplies the JDBC driver at runtime. The compiler plugin targets Java 25; the execution plugin runs our main class with the project’s dependencies.

3. Add the Book entity

File: src/main/java/org/kodejava/hibernate/Book.java

package org.kodejava.hibernate;

import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.Id;
import jakarta.persistence.Table;

@Entity
@Table(name = "books")
public class Book {
    @Id
    private Long id;

    @Column(nullable = false)
    private String title;

    protected Book() {
    }

    public Book(Long id, String title) {
        this.id = id;
        this.title = title;
    }

    public String getTitle() {
        return title;
    }
}

This is the entity introduced in article 1. Mapping annotations are on fields, so Hibernate accesses fields directly. A setter is not required for loading the title. The protected no-argument constructor allows the persistence provider to instantiate the entity. For now, the application assigns 1L as the identifier.

4. Configure the persistence unit

File: src/main/resources/META-INF/persistence.xml

<?xml version="1.0" encoding="UTF-8"?>
<persistence xmlns="https://jakarta.ee/xml/ns/persistence"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="https://jakarta.ee/xml/ns/persistence https://jakarta.ee/xml/ns/persistence/persistence_3_2.xsd"
             version="3.2">
    <persistence-unit name="book-catalog" transaction-type="RESOURCE_LOCAL">
        <provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
        <class>org.kodejava.hibernate.Book</class>
        <exclude-unlisted-classes>true</exclude-unlisted-classes>
        <properties>
            <property name="jakarta.persistence.jdbc.driver" value="org.h2.Driver"/>
            <property name="jakarta.persistence.jdbc.url" value="jdbc:h2:mem:book_catalog"/>
            <property name="jakarta.persistence.jdbc.user" value="sa"/>
            <property name="jakarta.persistence.jdbc.password" value=""/>
            <property name="jakarta.persistence.schema-generation.database.action" value="drop-and-create"/>
            <property name="hibernate.show_sql" value="true"/>
            <property name="hibernate.format_sql" value="true"/>
        </properties>
    </persistence-unit>
</persistence>

A persistence unit groups entity mappings and connection settings under one name. We explicitly register Book and disable discovery of unlisted entities so that the model is easy to follow.

RESOURCE_LOCAL means our application controls transactions through EntityTransaction. The H2 URL creates a named database in memory. Hibernate’s connection pool keeps connections available during the application; the database disappears when its last connection closes. Nothing is saved to a database file.

drop-and-create recreates the mapped schema when the persistence unit starts. Use it only for this disposable example: it can delete existing tables and data. Later, we will manage persistent schema changes with migrations. Hibernate detects the H2 SQL dialect from JDBC metadata, so no explicit dialect setting is needed.

The bootstrap and configuration approach follows Hibernate’s Jakarta Persistence quickstart.

5. Save and load a book

File: src/main/java/org/kodejava/hibernate/BookCatalogApp.java

package org.kodejava.hibernate;

import jakarta.persistence.EntityManager;
import jakarta.persistence.EntityManagerFactory;
import jakarta.persistence.EntityTransaction;
import jakarta.persistence.Persistence;

public class BookCatalogApp {
    public static void main(String[] args) {
        try (EntityManagerFactory factory =
                     Persistence.createEntityManagerFactory("book-catalog")) {
            saveBook(factory);
            loadBook(factory);
        }
    }

    private static void saveBook(EntityManagerFactory factory) {
        try (EntityManager entityManager = factory.createEntityManager()) {
            EntityTransaction transaction = entityManager.getTransaction();
            try {
                transaction.begin();
                entityManager.persist(new Book(1L, "Effective Java"));
                transaction.commit();
                System.out.println("Saved book: Effective Java");
            } catch (RuntimeException exception) {
                if (transaction.isActive()) {
                    transaction.rollback();
                }
                throw exception;
            }
        }
    }

    private static void loadBook(EntityManagerFactory factory) {
        try (EntityManager entityManager = factory.createEntityManager()) {
            Book book = entityManager.find(Book.class, 1L);
            if (book == null) {
                throw new IllegalStateException("Book 1 was not found");
            }
            System.out.println("Loaded book: " + book.getTitle());
        }
    }
}

Persistence.createEntityManagerFactory() finds META-INF/persistence.xml on the classpath and selects the unit named book-catalog. Create one factory for the application and close it at shutdown. Each EntityManager represents a separate persistence context and must also be closed. Jakarta Persistence 3.2 supports try-with-resources for both.

The write runs inside a transaction. Committing flushes the insert to H2. If the operation fails and the transaction is still active, we roll it back and propagate the failure.

The read uses a new entity manager, so it does not reuse the original persistence context’s managed book. A primary-key find() outside a transaction is permitted here because we are simply reading without a lock. In larger applications, transaction boundaries should follow the complete unit of work.

6. Run the application

From the directory containing pom.xml, run:

mvn clean compile exec:java

Maven downloads dependencies, compiles both Java files, copies resources into target/classes, and runs BookCatalogApp.

Expected application output:

Saved book: Effective Java
Loaded book: Effective Java

Hibernate also prints startup messages and SQL. Formatting may vary, but the SQL includes table creation, an insert, and a select:

create table books (
    id bigint not null,
    title varchar(255) not null,
    primary key (id)
)
insert into books (title, id) values (?, ?)
select b1_0.id, b1_0.title from books b1_0 where b1_0.id=?

Question marks are JDBC bind parameters, not missing values. Running the command again starts with a fresh in-memory database, so the assigned ID does not collide with a previous run.

If startup reports that no persistence provider exists for book-catalog, check the exact filename, the META-INF directory, the persistence-unit name, and the Hibernate dependency. If compilation reports that release 25 is unsupported, check the JDK shown by mvn -version. A warning about Hibernate’s built-in connection pool is expected for this small tutorial; production applications should configure a production connection pool.

Maven Dependencies

These are all direct library dependencies needed by this example. The complete POM above also pins the build plugins. Jakarta Persistence is supplied transitively by Hibernate Core; no separate driver installation or H2 server is required.

<dependencies>
    <dependency>
        <groupId>org.hibernate.orm</groupId>
        <artifactId>hibernate-core</artifactId>
        <version>7.4.17.Final</version>
    </dependency>
    <dependency>
        <groupId>com.h2database</groupId>
        <artifactId>h2</artifactId>
        <version>2.5.252</version>
        <scope>runtime</scope>
    </dependency>
</dependencies>

What Is Hibernate ORM?

When you use JDBC to read a row from a database, you normally write a SQL query, execute it, and copy the values from the ResultSet into a Java object. If your application has classes such as Book, Author, and Publisher, you repeat this kind of mapping for each class.

Hibernate ORM is a Java framework that handles much of this mapping. You describe how your Java classes correspond to tables, and Hibernate uses that information to load objects and save changes. This series uses Java 25 and Hibernate ORM 7.4.15.Final, the latest stable release as of November 9, 2026. Hibernate ORM 7.4 implements Jakarta Persistence 3.2. See the Hibernate ORM release notes.

What does ORM mean?

ORM stands for object-relational mapping. It connects the way Java represents data as objects with the way a relational database stores data in tables.

For a simple book catalog, the mapping looks like this.

Java Database
Book class books table
One Book object One row in books
id field id primary key column
title field title column

A class that Hibernate can persist is called an entity. Here is the first entity in our catalog.

package org.kodejava.hibernate;

import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.Id;
import jakarta.persistence.Table;

@Entity
@Table(name = "books")
public class Book {
    @Id
    private Long id;

    @Column(nullable = false)
    private String title;

    protected Book() {
    }

    public Book(Long id, String title) {
        this.id = id;
        this.title = title;
    }

    public String getTitle() {
        return title;
    }
}
  • @Entity marks Book as a persistent entity.
  • @Table(name = "books") maps the entity to the books table.
  • @Id identifies the field that maps to the primary key. This example assigns the ID in the constructor.
  • @Column(nullable = false) declares the title column as non-nullable in the mapping.

Hibernate can read and write the mapped fields directly because the mapping annotations are on the fields. The protected no-argument constructor allows the persistence provider to instantiate a Book when it loads data.

How does Hibernate save an object?

After Hibernate is configured, you can use an EntityManager to work with entities. The following snippet assumes an existing EntityManager and an active transaction.

Book book = new Book(1L, "Effective Java");
entityManager.persist(book);

Calling persist() makes the new Book a managed entity. Hibernate now tracks it in the persistence context. When Hibernate flushes the context, typically as part of committing the transaction, it executes an SQL statement similar to this one.

insert into books (title, id) values (?, ?)

Hibernate binds the values from the object to those parameters and executes the statement through JDBC. You can load a book by its primary key with entityManager.find(Book.class, 1L). If the persistence context already manages that book, Hibernate can return it directly. Otherwise, Hibernate can load it from the database, and find() returns null if the book does not exist.

What is the difference between Jakarta Persistence and Hibernate?

Jakarta Persistence, often called JPA, defines standard annotations and interfaces such as @Entity, @Id, and EntityManager. Hibernate ORM implements that standard and provides its own API, including SessionFactory and Session.

We will start with Jakarta Persistence so you can learn the standard mapping and transaction APIs. Later articles will use Hibernate-specific features where they help solve a concrete problem, such as inspecting SQL activity or tuning fetch behavior. The Hibernate ORM Javadocs describe both APIs.

Where does JDBC fit?

Hibernate uses JDBC to communicate with the database. With plain JDBC, you usually write the SQL and map the results yourself. With Hibernate, you provide entity mappings, and Hibernate handles many routine operations, such as inserting a row or finding it by primary key.

The SQL still matters. Loading a list of books and then accessing each book’s author can trigger extra queries. Later in the series, we will inspect the generated SQL and see how a fetch join can avoid that pattern.

In the next article, we will create a Maven project, configure an in-memory H2 database, and run the Book example from start to finish. We will use plain Java to make the Hibernate configuration and transaction boundaries visible.

Maven Dependencies

Add the following dependency inside the <dependencies> section of your pom.xml. Hibernate Core brings in the Jakarta Persistence API transitively, including the annotations used above. To run the example against a database, you will also need a JDBC driver. We will add the H2 driver in the next article.

<dependency>
    <groupId>org.hibernate.orm</groupId>
    <artifactId>hibernate-core</artifactId>
    <version>7.4.15.Final</version>
</dependency>

How do I handle Detached objects and reattach them using Hibernate?

In Hibernate, detached objects are objects that were previously associated with a Hibernate Session, but that Session has since been closed, leaving the object in a detached state. Detached objects are not currently managed by any Session, so they are not automatically synchronized with the database. If you want to reattach these objects to a new session, Hibernate provides a couple of operations to handle them:


1. Using Session.update()

The update() method reattaches a detached object to the current session and marks it as persistent. The object must represent a row that already exists in the database. If there are issues (e.g., the object doesn’t exist in the database), an exception will be thrown.

Example:

Session session = sessionFactory.openSession();
Transaction transaction = session.beginTransaction();

MyEntity detachedEntity = getDetachedEntity(); // Detached entity

// Reattach the detached entity to the session
session.update(detachedEntity);

// After reattachment, changes to the entity will be synchronized with the database
detachedEntity.setSomeField("newValue");

transaction.commit();
session.close();

Note: Use update() only when you are sure that the detached entity exists in the database.


2. Using Session.merge()

The merge() method is often a better approach for reattaching detached objects, as it handles the entity more flexibly. If the object exists in the database, it merges the changes from the detached entity into the persistent object in the session. If it doesn’t exist, it creates a new database row.

Example:

Session session = sessionFactory.openSession();
Transaction transaction = session.beginTransaction();

MyEntity detachedEntity = getDetachedEntity(); // Detached entity

// Merge the detached entity with the session
MyEntity mergedEntity = (MyEntity) session.merge(detachedEntity);

// Use the merged entity for further operations
mergedEntity.setSomeField("anotherValue");

transaction.commit();
session.close();

Key Differences Between update() and merge():
– update() can throw NonUniqueObjectException if an object with the same identifier is already associated with the session.
– merge() does not throw an exception—it creates a new instance in the session if an object with the same identifier is already associated.


3. Using Session.saveOrUpdate() (Not Recommended for Detached Objects)

The saveOrUpdate() method can accept both transient and detached objects. For detached objects, it either updates the corresponding row in the database or saves it if it’s not already present. However, this method is not as commonly used for handling detached objects as update() or merge().

Example:

Session session = sessionFactory.openSession();
Transaction transaction = session.beginTransaction();

MyEntity detachedEntity = getDetachedEntity(); // Detached entity

// Save or update the detached entity
session.saveOrUpdate(detachedEntity);

transaction.commit();
session.close();

Note: This method can be less predictable when dealing with detached objects compared to merge().


Common Scenarios and Approaches

  • When you need to reattach a detached object and persist its changes: Use merge().
  • When you know the object already exists in the database: Use update().
  • Avoid session conflicts: If a different object with the same identifier is already in the new session, prefer merge() because update() will result in an exception.

Best Practices

  • Ensure entities have properly defined identifiers (@Id) to avoid Hibernate-related issues when reattaching.
  • Use merge() when you are uncertain about whether the object is persistent or detached, as it adapts to the situation.
  • Keep sessions short and transactions small to reduce occurrences of detached objects.

By understanding and implementing these methods appropriately, you can effectively handle detached objects and ensure smooth database operations in a Hibernate-based application.

How do I batch insert or update data using Hibernate efficiently?

Batch inserting or updating data efficiently with Hibernate can significantly improve performance, especially when dealing with large datasets. Below are best practices and steps to achieve this:


1. Enable Hibernate Batch Processing

  • Configure Hibernate for batch processing by setting the hibernate.jdbc.batch_size property in your Hibernate configuration:
hibernate.jdbc.batch_size=20

This specifies the number of SQL statements to batch before executing them.


2. Use Stateless Sessions

  • Stateless sessions in Hibernate can be used for bulk operations since they don’t maintain a persistent context (no caching, dirty checking, etc.), resulting in better performance for inserts and updates:
try (StatelessSession statelessSession = sessionFactory.openStatelessSession()) {
    statelessSession.beginTransaction();
    for (Entity entity : entities) {
        statelessSession.insert(entity); // For batch inserts
    }
    statelessSession.getTransaction().commit();
}

However, keep in mind that StatelessSession sacrifices some features of the Hibernate Session, such as caching.


3. Control the Flush Mode

  • When using a traditional Session, set the flush mode to COMMIT to reduce the frequency of session flushing:
session.setFlushMode(FlushMode.COMMIT);

This avoids automatic flushing after every operation and significantly improves performance.


4. Batch Save or Update

  • Process entities in chunks and manually flush and clear the session to prevent memory overhead and ensure efficient batch execution:
int batchSize = 20; // Define batch size
Session session = sessionFactory.openSession();
session.beginTransaction();

for (int i = 0; i < entities.size(); i++) {
    session.saveOrUpdate(entities.get(i));

    if (i % batchSize == 0 && i > 0) { // Execute batch
        session.flush();
        session.clear(); // Clear the persistence context
    }
}

session.getTransaction().commit();
session.close();

This approach avoids storing too many entities in memory.


5. Use Native SQL for Bulk Operations

  • For massive updates that don’t require Hibernate’s lifecycle benefits, native SQL queries might be more efficient:
String updateQuery = "UPDATE Entity SET status = :status WHERE condition = :condition";
Query query = session.createQuery(updateQuery);
query.setParameter("status", newStatus);
query.setParameter("condition", condition);
int rowsUpdated = query.executeUpdate();

This approach avoids loading entities into memory.


6. Optimize JDBC Batch Settings

  • Configure JDBC for optimal performance when batching. Ensure that the database driver supports batching and is properly configured.

7. Avoid Cascading with Large Batches

  • Cascading operations (e.g., CascadeType.ALL) can cause performance degradation if there are many associated entities. Instead, manage the lifecycle of associations manually.

8. Index SQL Statements Properly

  • Ensure that the database tables involved in batch updates or inserts have the appropriate indexes for your operations.

9. Monitor and Test

  • Use Hibernate logs to monitor SQL being executed:
hibernate.show_sql=true
hibernate.format_sql=true
hibernate.use_sql_comments=true
  • Enable Hibernate statistics or use a profiling tool to analyze the performance:
Session session = sessionFactory.openSession();
Statistics stats = sessionFactory.getStatistics();
stats.setStatisticsEnabled(true);
  • Regularly test to find the optimal batch size for your environment, as it depends on factors like memory and database capabilities.

Summary

By batching operations, clearing the persistence context, and tuning Hibernate and database configurations, you can optimize the performance of batch inserts or updates. Large datasets will benefit greatly when you combine batching with techniques like StatelessSession and native SQL for non-critical use cases.

How do I customize table and column names using Hibernate annotations?

In Hibernate, you can customize table and column names using JPA annotations such as @Table and @Column. These annotations allow you to define how your entity classes map to the database tables and columns. Here’s how you can do it:

Customize the Table Name

To specify a custom table name, use the @Table annotation on the class level. You define the table name by setting the name attribute of the @Table annotation.

import jakarta.persistence.Entity;
import jakarta.persistence.Table;

@Entity
@Table(name = "custom_table_name")
public class MyEntity {
    // Other fields and methods
}

In this example, the associated database table for the MyEntity class will be named custom_table_name.

Customize the Column Names

To customize column names, use the @Column annotation on the field or property. You can specify the name of the column by setting the name attribute of the annotation.

import jakarta.persistence.Entity;
import jakarta.persistence.Id;
import jakarta.persistence.Column;

@Entity
public class MyEntity {

    @Id
    private Long id;

    @Column(name = "custom_column_name")
    private String myField;

    // Getters and Setters
}

Here, the myField field will map to the column custom_column_name in the database.

Complete Example

Below is a complete example demonstrating both:

import jakarta.persistence.Entity;
import jakarta.persistence.Id;
import jakarta.persistence.Table;
import jakarta.persistence.Column;

@Entity
@Table(name = "custom_table_name")
public class MyEntity {

    @Id
    private Long id;

    @Column(name = "custom_column_name")
    private String customField;

    @Column(name = "date_of_creation", nullable = false, unique = true)
    private String creationDate;

    // Getters and Setters
}
  • The @Table annotation maps the class to a custom table name (custom_table_name).
  • The @Column annotation maps the fields to custom column names (custom_column_name and date_of_creation).
  • Optional attributes like nullable, unique, length, etc., allow further customization.

Notes

  1. Default Naming: If you omit the @Table or @Column annotations, Hibernate will use default naming strategies (usually camelCase names are converted to snake_case for the database).
  2. Schema or Catalog: You can also specify a schema or catalog in the @Table annotation:
    @Table(name = "custom_table_name", schema = "my_schema")
    
  3. Column Options: The @Column annotation includes additional options like:
    • nullable: Whether the column allows nulls.
    • unique: Whether the column should have a unique constraint.
    • length: The length of the column (useful for VARCHAR columns).
    • precision and scale: For DECIMAL and NUMERIC columns.

This level of customization gives you precise control over how your Java entities are mapped to database tables and columns.