Hibernate

Language: Java

Data

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.

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

Installation

maven: Add hibernate-core dependency in pom.xml
gradle: Add implementation 'org.hibernate:hibernate-core:5.6.15.Final' in build.gradle

Usage

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.

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.

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.

Error Handling

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.