Hibernate

About

  • Hibernate is a powerful Object-Relational Mapping (ORM) framework for Java.

  • It provides an implementation of the JPA specification (but it also existed before JPA was created).

  • Hibernate is both:

    • A JPA Provider (when used via javax.persistence APIs)

    • A full-featured standalone ORM (with its own Hibernate APIs beyond JPA)

Thus, Hibernate is both a standard JPA implementation and an extended ORM toolkit.

Features of Hibernate

Feature
Details

ORM Mapping

Maps Java objects to database tables using annotations/XML.

Automatic SQL Generation

Developers don't need to manually write SQL for most operations (save, update, delete).

Transparent Persistence

Java objects can be persisted without being aware of Hibernate-specific APIs.

Caching

Built-in first-level (mandatory) and optional second-level caching.

Lazy Loading

Association fetching is deferred until actually needed.

Dirty Checking

Hibernate automatically detects changes to managed objects and updates the database accordingly.

HQL (Hibernate Query Language)

Object-oriented SQL-like language that works with entity names and fields instead of table/column names.

Criteria API

Programmatic, typesafe query creation (prior to JPA Criteria).

Transaction Management

Supports JTA, JDBC, and manual transactions.

Schema Generation and Validation

Auto-create/update database schemas based on entity mappings.

Custom Interceptors and Event Listeners

Customize behavior during persistence events.

Hibernate vs JPA

Aspect
JPA
Hibernate

Definition

Java standard/specification (interface only)

Actual software framework (implementation)

APIs

Only standard APIs (e.g., EntityManager)

Both JPA standard APIs + Hibernate-specific APIs (e.g., Session)

Vendor

No vendor — just a spec maintained by Jakarta EE (previously Oracle)

Red Hat developed and maintains Hibernate

Usage

Needs an implementation like Hibernate, EclipseLink, etc.

Hibernate can work with or without JPA APIs

Hibernate Architecture

Hibernate is layered internally. Here’s a breakdown:

Layer
Responsibility

Session Factory

Startup object that initializes Hibernate internals, manages caches, and creates Session objects. Immutable, thread-safe object for creating Session instances. Very expensive to create and must be singleton.

Session

Core Hibernate object for CRUD operations, transaction boundaries, query execution. Lightweight, not thread-safe. Used for a single unit of work (transaction).

Persistence Context

Cache of managed entities (attached to Session).

Transaction Manager

Bridges Hibernate with JTA or JDBC transaction APIs.

Connection Provider

Manages database connection pooling.

Dialect

Abstracts differences between database vendors (e.g., MySQL vs Oracle).

Entity Persister

Responsible for mapping a Java entity to a table and generating SQL.

Query Translator

Parses HQL/JPQL into SQL.

Cache Layer

Provides first-level cache (mandatory) and optional second-level cache integrations (like EhCache, Infinispan).

Interceptor

Provides callbacks on entity life-cycle events.

Event System

Internally Hibernate uses an event-driven model (pre-insert, post-load, etc.).

How Hibernate Works on a High Level ?

  1. Configuration Phase:

    • Read hibernate.cfg.xml (or Spring Boot properties).

    • Scan entity classes annotated with @Entity.

    • Build metadata and mappings.

  2. SessionFactory Creation:

    • Heavyweight object, created once per application.

    • Holds database connection pool, caching, dialect, etc.

  3. Session Management:

    • For each unit of work (typically a request/transaction), a Session is created.

    • It manages the Persistence Context (the cache of currently managed entities).

  4. Transaction Control:

    • Begin transaction.

    • Perform create, read, update, delete operations.

    • Commit or rollback transaction.

  5. SQL Generation and Execution:

    • Hibernate generates SQL behind the scenes (select, insert, update, delete).

    • SQL is executed using JDBC under the hood.

  6. Flush and Synchronization:

    • At commit or flush time, Hibernate synchronizes in-memory entity changes with the database.

  7. Session Close:

    • After transaction commit/rollback, Session is closed.

    • Persistence Context is cleared.

Hibernate Annotations Beyond Standard JPA

Hibernate adds its own annotations (not portable across JPA providers):

Annotation
Purpose

@Type

Specify custom Hibernate-specific types.

@CreationTimestamp

Auto-populate a timestamp on entity creation.

@UpdateTimestamp

Auto-populate a timestamp on entity update.

@DynamicInsert

Generate SQL insert only with non-null fields.

@DynamicUpdate

Generate SQL update only with modified fields.

@Formula

Map an entity property to a SQL subquery.

@NaturalId

Mark an alternative key (natural ID) for the entity.

Hibernate Caching Architecture

Cache Type
Description

First-Level Cache

Mandatory. Every Session has a first-level cache (persistence context). No configuration needed.

Second-Level Cache

Optional. Shared between sessions. Requires external cache provider (e.g., Ehcache, Infinispan).

Query Cache

Caches the results of queries (especially useful for read-heavy systems). Must be enabled separately.

Hibernate Fetch Strategies

Hibernate supports:

  • Lazy Fetching (default for associations): Load associated entities only when accessed.

  • Eager Fetching: Load associated entities immediately with the parent entity.

Fetching modes:

  • Join Fetch (using SQL joins)

  • Select Fetch (separate select statements)

Hibernate allows tuning fetch mode using @Fetch(FetchMode.SELECT) or @Fetch(FetchMode.JOIN).

Hibernate Session Life Cycle

Hibernate manages the state of an entity through different phases:

State
Meaning
Example

Transient

New object not associated with any Hibernate Session; not persisted yet.

new User()

Persistent

Object is associated with an open Session and tracked; any changes are automatically detected and synchronized to DB.

session.save(user)

Detached

Object was once associated with a Session but Session is closed; changes are not automatically detected.

After session.close()

Removed

Object is scheduled for deletion but might still exist in Session until flush.

session.delete(user)

Hibernate in Spring Boot Context

When using Hibernate inside Spring Boot:

  • Hibernate is automatically configured via spring-boot-starter-data-jpa.

  • Default Hibernate properties are applied unless overridden.

  • Hibernate SessionFactory is managed internally by Spring's EntityManagerFactory.

  • We rarely interact directly with Session — we use JPA's EntityManager which is backed by Hibernate Session.

Spring Boot default Hibernate DDL options:

  • validate, update, create, create-drop, none.

spring.jpa.hibernate.ddl-auto=update

Advanced Concepts

Batch Processing

  • Hibernate can batch multiple SQL statements together to reduce database round trips.

  • Example:

hibernate.jdbc.batch_size=30

Hibernate will batch up to 30 insert/update statements into a single network call.

Example

Session session = sessionFactory.openSession();
Transaction tx = session.beginTransaction();
for (int i = 0; i < 1000; i++) {
    Employee emp = new Employee("Employee " + i);
    session.save(emp);
    if (i % 30 == 0) { // Flush and clear batch every 30 records
        session.flush();
        session.clear();
    }
}
tx.commit();
session.close();

Batch processing improves performance drastically for bulk operations.

Stateless Session

  • StatelessSession is a special Hibernate session that does not maintain a persistence context (no cache, no dirty checking).

  • It behaves more like plain JDBC.

Example

StatelessSession session = sessionFactory.openStatelessSession();
Transaction tx = session.beginTransaction();
Employee emp = new Employee("Stateless Employee");
session.insert(emp);
tx.commit();
session.close();

Useful for batch inserts/updates where tracking every object is costly.

Multi-Tenancy Support

Hibernate supports multi-tenancy models:

Strategy
Meaning

DATABASE

Different tenants use different physical databases.

SCHEMA

Same DB, but different schemas for tenants.

DISCRIMINATOR

Same table, a special column distinguishes tenant records.

Spring Boot + Hibernate can configure multi-tenant systems using MultiTenantConnectionProvider and CurrentTenantIdentifierResolver.

Last updated