Skip to content

Hibernate

The JPA implementation that defined ORM on the JVM.

Data & AnalyticsDataJava

What it is

Hibernate is a powerful Object-Relational Mapping (ORM) framework for Java that simplifies database interactions by mapping Java objects to relational database tables.

Hibernate allows developers to interact with databases using Java objects rather than SQL. It provides features like automatic table generation, HQL (Hibernate Query Language), transaction management, and caching.

Watch for
N+1 queries and LazyInitializationException — the two problems everyone meets
Licence
LGPL 2.1

When to use it

The question documentation cannot answer for you — because it cannot recommend something else.

Reach for it when

  • Rich domain models where you want objects rather than result sets
  • The team already knows JPA, and Spring Data will sit on top of it

Look elsewhere when

  • Read-heavy reporting where you want the SQL to be exactly what you wrote — use jOOQ or plain JDBC
  • The team does not understand lazy loading and transaction boundaries; the failure modes are subtle

Installation

Add hibernate-core dependency in pom.xml

Getting started

The smallest useful thing you can do with it, and what each part means.

Mapping an entity
// User.java
import jakarta.persistence.Entity;
import jakarta.persistence.Id;

@Entity
public class User {
    @Id
    private Long id;
    private String name;
    private String email;
    // getters and setters
}
Defines a simple `User` entity that maps to a database table using JPA annotations.
Creating Hibernate SessionFactory
// HibernateUtil.java
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

public class HibernateUtil {
    private static final SessionFactory sessionFactory =
        new Configuration().configure().buildSessionFactory();

    public static SessionFactory getSessionFactory() {
        return sessionFactory;
    }
}
Creates a singleton `SessionFactory` which is used to open sessions for database operations.

Advanced usage

Where the library earns its place over a simpler alternative.

Saving an entity
import org.hibernate.Session;
import org.hibernate.Transaction;

Session session = HibernateUtil.getSessionFactory().openSession();
Transaction tx = session.beginTransaction();
User user = new User();
user.setId(1L);
user.setName("Alice");
session.save(user);
tx.commit();
session.close();
Demonstrates saving a `User` entity to the database using Hibernate session and transaction.
Querying with HQL
Session session = HibernateUtil.getSessionFactory().openSession();
List<User> users = session.createQuery("FROM User WHERE name = :name", User.class)
    .setParameter("name", "Alice")
    .list();
session.close();
Uses Hibernate Query Language (HQL) to fetch users with a specific name.
Updating an entity
Session session = HibernateUtil.getSessionFactory().openSession();
Transaction tx = session.beginTransaction();
User user = session.get(User.class, 1L);
user.setEmail("alice@example.com");
session.update(user);
tx.commit();
session.close();
Updates an existing user entity in the database.
Deleting an entity
Session session = HibernateUtil.getSessionFactory().openSession();
Transaction tx = session.beginTransaction();
User user = session.get(User.class, 1L);
session.delete(user);
tx.commit();
session.close();
Deletes a user entity from the database.

Errors and fixes

The failures you are most likely to hit, and what actually resolves them.

org.hibernate.LazyInitializationException
Occurs when accessing uninitialized lazy-loaded associations outside of session. Ensure session is open or fetch eagerly.
org.hibernate.HibernateException
General Hibernate exception. Check configuration, mappings, and session handling.
ConstraintViolationException
Occurs when database constraints (e.g., unique, not null) are violated. Validate data before saving.

Best practices

  • Use JPA annotations for entity mapping for portability.
  • Always manage transactions explicitly for consistency.
  • Close sessions to release database connections.
  • Use caching (first-level and second-level) to improve performance.
  • Prefer parameterized queries or HQL to prevent SQL injection.

Alternatives

Comparable options, and the reason you would pick one over the other.

Background

Why it exists, and what it was reacting to.

Hibernate was created to solve the problem of manual JDBC code and boilerplate SQL queries. It provides a high-level abstraction for database operations, supports caching, lazy loading, and transaction management, making Java applications more maintainable and scalable.