The Wild

How to Set Up Hibernate in a Maven Project

· 4 min read · Mammals

In this article
  1. Why Use Hibernate with Maven?
  2. Step 1: Add Hibernate Dependencies to pom.xml
  3. Step 2: Configure Hibernate (hibernate.cfg.xml)
  4. Step 3: Create an Entity Class
  5. Step 4: Build a SessionFactory
  6. Common Problems and Solutions
  7. Alternative Configuration: programmatic and properties file
  8. Frequently Asked Questions
  9. Wrapping Up

To set up Hibernate in a Maven project, add the Hibernate Core dependency (and a database driver) to your pom.xml, then configure a Hibernate SessionFactory using either a hibernate.cfg.xml file or programmatic configuration. Below is a complete walkthrough covering dependencies, configuration, entity mapping, and common pitfalls.

Why Use Hibernate with Maven?

Hibernate is an Object-Relational Mapping (ORM) framework that simplifies database access in Java by mapping Java classes to database tables. Maven manages dependencies and builds automatically, so combining the two gives you a reproducible project setup where Hibernate’s libraries and their transitive dependencies (like the JPA API and logging) are pulled in without manual JAR management.

Maven also handles version conflicts and makes it easy to switch databases by changing a single dependency. For example, moving from MySQL to PostgreSQL only requires swapping the driver artifact.

Step 1: Add Hibernate Dependencies to pom.xml

Open your pom.xml and add the following inside the <dependencies> section. Use the latest stable Hibernate 6.x version (check Maven Central for the current release, e.g., 6.5.2.Final).

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

You also need a JDBC driver for your database. For MySQL:

<dependency>
    <groupId>com.mysql</groupId>
    <artifactId>mysql-connector-j</artifactId>
    <version>8.4.0</version>
    <scope>runtime</scope>
</dependency>

For PostgreSQL, use org.postgresql:postgresql. If you plan to use JPA annotations (which Hibernate implements), you may also add jakarta.persistence:jakarta.persistence-api, but Hibernate Core already includes it transitively.

Step 2: Configure Hibernate (hibernate.cfg.xml)

Create a hibernate.cfg.xml file in src/main/resources. This XML file tells Hibernate how to connect to your database and which dialect to use. A minimal example for MySQL:

<?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>
    <property name="hibernate.connection.driver_class">com.mysql.cj.jdbc.Driver</property>
    <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/mydb</property>
    <property name="hibernate.connection.username">root</property>
    <property name="hibernate.connection.password">secret</property>
    <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
    <property name="hibernate.hbm2ddl.auto">update</property>
    <property name="hibernate.show_sql">true</property>
  </session-factory>
</hibernate-configuration>

For Hibernate 6, the dialect class names have changed (e.g., MySQLDialect instead of MySQL5Dialect). Using the wrong dialect is a common cause of runtime errors.

Step 3: Create an Entity Class

Define a plain Java class annotated with @Entity and @Id. Example:

import jakarta.persistence.*;

@Entity
@Table(name = "products")
public class Product {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String name;
    private Double price;
    // getters and setters
}

Hibernate will map this class to the products table. If you use hibernate.hbm2ddl.auto=update, Hibernate will create or update the table schema automatically based on your annotations.

Step 4: Build a SessionFactory

To interact with the database, you need a SessionFactory. The standard way is to load the configuration from the XML file:

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

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

    private static SessionFactory buildSessionFactory() {
        try {
            return new Configuration().configure().buildSessionFactory();
        } catch (Throwable ex) {
            throw new ExceptionInInitializerError(ex);
        }
    }

    public static SessionFactory getSessionFactory() {
        return sessionFactory;
    }
}

Then you can open a Session and begin a transaction:

Session session = HibernateUtil.getSessionFactory().openSession();
session.beginTransaction();
session.save(new Product("Laptop", 999.99));
session.getTransaction().commit();
session.close();

Common Problems and Solutions

  • ClassNotFoundException for driver – Ensure the JDBC driver dependency is present and not marked as provided.
  • Wrong dialect – Use the dialect matching your Hibernate version and database. For Hibernate 6, MySQL uses org.hibernate.dialect.MySQLDialect.
  • Table not found – Set hibernate.hbm2ddl.auto=update to auto-create tables, or run SQL scripts manually.
  • Multiple versions of JPA – Hibernate 6 requires Jakarta Persistence 3.x. If you have old javax.persistence dependencies, remove them.
  • SessionFactory is expensive – Create it once and reuse it; never create a new one per operation.

Alternative Configuration: programmatic and properties file

Instead of XML, you can configure Hibernate programmatically using Configuration methods:

Configuration cfg = new Configuration()
    .setProperty("hibernate.connection.driver_class", "com.mysql.cj.jdbc.Driver")
    .setProperty("hibernate.connection.url", "jdbc:mysql://localhost:3306/mydb")
    .setProperty("hibernate.dialect", "org.hibernate.dialect.MySQLDialect")
    .addAnnotatedClass(Product.class);
SessionFactory sf = cfg.buildSessionFactory();

You can also use a hibernate.properties file in the classpath. This is useful when you want to avoid XML and keep configuration in a simple key-value format.

Frequently Asked Questions

Do I need both Hibernate and JPA dependencies?

No. Hibernate Core includes the JPA API (jakarta.persistence) as a transitive dependency. Adding a separate JPA dependency can cause version conflicts. Just use hibernate-core.

Why do I get “Unable to load class [org.hibernate.dialect.MySQL5Dialect]”?

That dialect class was removed in Hibernate 6. Use the new dialect names like org.hibernate.dialect.MySQLDialect. Check the Hibernate documentation for the correct dialect for your database version.

How do I connect Hibernate to an in-memory database like H2?

Add the H2 dependency (com.h2database:h2) and set the URL to jdbc:h2:mem:test and driver to org.h2.Driver. The dialect is org.hibernate.dialect.H2Dialect.

What is the difference between hibernate.hbm2ddl.auto values?

update updates the schema without dropping existing tables; create drops and recreates tables on startup; create-drop drops tables when the SessionFactory closes; validate only checks the schema. For production, validate or manual migration is recommended.

Can I use Hibernate without a XML config file?

Yes. You can configure everything programmatically or via a hibernate.properties file. Many Spring Boot projects use application.properties with Hibernate properties like spring.jpa.hibernate.ddl-auto.

Why does Hibernate print SQL but not execute it?

If hibernate.show_sql=true, Hibernate logs the SQL. If it doesn’t appear in the database, check that you committed the transaction and that the session is flushed. Also, ensure the entity is actually persisted (e.g., using session.save() or persist()).

Wrapping Up

Setting up Hibernate in Maven is straightforward: add the correct dependencies, create a configuration file, define an entity, and build a SessionFactory. Once you understand the core steps, you can expand to more advanced features like caching, criteria queries, and mapping relationships. Always keep your Hibernate version and database driver compatible, and test your setup with a simple CRUD operation before building complex logic.