Skip to main content

hibernate sample application with example

Building a Production-Grade Hibernate Sample Application

Hibernate Application Architecture Flow Hibernate Application Architecture Flow 1 Configuration Initialization Parse XML metadata and connection properties during startup. 2 SessionFactory Creation Instantiate the thread-safe global cache and SQL factory. 3 Session Acquisition Open a short-lived, single-threaded unit of work per request. 4 Transaction & Operations Execute data persistence and query operations via the session. 5 Session Closure Close the session safely to prevent memory leaks and bloat.
Figure: Hibernate Application Architecture Flow

Object-Relational Mapping (ORM) frameworks bridge the gap between object-oriented domain models and relational database management systems (RDBMS). In the Java ecosystem, Hibernate serves as the industry standard implementation of the Java Persistence API (JPA). Writing raw JDBC boilerplate code requires managing manual connection pooling, writing repetitive mapping logic, and manually translating ResultSets into domain entities. Hibernate automates these operations, allowing software engineers to focus on business logic rather than database infrastructure.

Pick a language, then press Listen.

This tutorial provides a complete, production-grade guide to building a Hibernate sample application from scratch. We will break down core Hibernate components, set up configuration files, write entity classes, execute data persistence operations, and handle real-world architectural edge cases.

Core Architectural Components of Hibernate

Understanding Hibernate requires mastering its primary architectural interfaces. These objects govern the lifecycle of database interactions, memory management, and thread synchronization.

Configuration

The Configuration object represents the bootstrap phase of a Hibernate application. It reads mapping metadata and connection properties from configuration files (traditionally hibernate.cfg.xml or programmatic properties) and initializes the environment. Because this object parses XML descriptors and initializes metadata registries, it should only be instantiated once during application startup.

SessionFactory

The SessionFactory is a heavy, thread-safe object derived from the Configuration instance. It caches generated SQL statements, metadata, and second-level cache data across the entire application. In a standard enterprise architecture, an application requires exactly one SessionFactory per database. If your system connects to multiple data sources, you must instantiate multiple SessionFactory instances, keeping them alive for the entire lifespan of the JVM process.

Session

A Session represents a single-threaded, short-lived unit of work with the database. It wraps a JDBC connection and acts as a factory for transactions, queries, and criteria objects. Sessions are not thread-safe and must never be shared across concurrent threads. Opening and closing sessions efficiently prevents connection leaks and memory bloat within high-throughput environments. For advanced container-managed applications, you might integrate deployment strategies similar to those found when executing a JNDI configuration for Tomcat 9 with Oracle.

Transaction

The Transaction interface abstracts underlying database transactions. While executing read-only queries does not strictly require a transaction, any data modification operations (INSERT, UPDATE, DELETE) must occur within an active transaction boundary. This guarantees ACID properties across operations.

Query and Criteria

Hibernate provides two primary mechanisms for retrieving data dynamically: Hibernate Query Language (HQL) and the Criteria API. HQL is an object-oriented dialect similar to SQL that operates on entity classes and properties instead of tables and columns. The Criteria API provides a programmatic, type-safe approach to constructing queries dynamically.

Comparison: Hibernate Core Interfaces

Interface / Component Thread Safety Lifespan Primary Responsibility
Configuration Not Thread-Safe Bootstrap / One-time Parses configuration files and sets up metadata.
SessionFactory Thread-Safe Application Lifetime Heavyweight cache for generated SQL and database metadata.
Session Not Thread-Safe Short-lived (Per Request / Transaction) Wraps a JDBC connection, handles CRUD operations.
Transaction Not Thread-Safe Very Short-lived Manages atomic units of work and rollback policies.

Step-by-Step Implementation of a Hibernate Sample Application

To build this sample application, configure a standard Java project (Maven or Gradle) with your preferred IDE. For modern Java developments involving immutable data structures, you can align your domain models with Java 17 Records and Pattern Matching with Examples, though entities require mutable standard classes for dirty-checking.

Step 1: Add Dependencies (Maven pom.xml)

Add the required Hibernate core and MySQL connector dependencies to your project configuration.

<dependencies>
    <!-- Hibernate Core -->
    <dependency>
        <groupId>org.hibernate.orm</groupId>
        <artifactId>hibernate-core</artifactId>
        <version>6.2.7.Final</version>
    </dependency>

    <!-- MySQL Connector -->
    <dependency>
        <groupId>com.mysql</groupId>
        <artifactId>mysql-connector-j</artifactId>
        <version>8.0.33</version>
    </dependency>
</dependencies>

Step 2: Create the Hibernate Configuration File

Create a file named hibernate.cfg.xml inside your src/main/resources directory. This file defines database connection properties and dialect settings.

<?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>
        <!-- JDBC Database connection settings -->
        <property name="connection.driver_class">com.mysql.cj.jdbc.Driver</property>
        <property name="connection.url">jdbc:mysql://localhost:3306/hibernate_db?useSSL=false&serverTimezone=UTC</property>
        <property name="connection.username">root</property>
        <property name="connection.password">password</property>

        <!-- JDBC connection pool settings -->
        <property name="connection.pool_size">10</property>

        <!-- SQL dialect -->
        <property name="dialect">org.hibernate.dialect.MySQLDialect</property>

        <!-- Echo all executed SQL to stdout -->
        <property name="show_sql">true</property>
        <property name="format_sql">true</property>

        <!-- Drop and re-create the database schema on startup if needed -->
        <property name="hbm2ddl.auto">update</property>

        <!-- Entity mappings -->
        <mapping class="com.javatbrains.entity.Employee"/>
    </session-factory>
</hibernate-configuration>

Step 3: Define the Entity Class

Create an annotated Java class representing a database table using standard JPA annotations.

package com.javatbrains.entity;

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

@Entity
@Table(name = "employee")
public class Employee {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "id")
    private int id;

    @Column(name = "first_name")
    private String firstName;

    @Column(name = "last_name")
    private String lastName;

    @Column(name = "email")
    private String email;

    public Employee() {}

    public Employee(String firstName, String lastName, String email) {
        this.firstName = firstName;
        this.lastName = lastName;
        this.email = email;
    }

    // Getters and Setters
    public int getId() { return id; }
    public void setId(int id) { this.id = id; }

    public String getFirstName() { return firstName; }
    public void setFirstName(String firstName) { this.firstName = firstName; }

    public String getLastName() { return lastName; }
    public void setLastName(String lastName) { this.lastName = lastName; }

    public String getEmail() { return email; }
    public void setEmail(String email) { this.email = email; }

    @Override
    public String toString() {
        return "Employee [id=" + id + ", firstName=" + firstName + ", lastName=" + lastName + ", email=" + email + "]";
    }
}

Step 4: Create the Main Application Runner

Write the execution class to initialize the SessionFactory, create a Session, start a transaction, and persist an entity.

package com.javatbrains;

import com.javatbrains.entity.Employee;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;

public class HibernateApplication {

    public static void main(String[] args) {
        // Step 1: Create Configuration
        Configuration configuration = new Configuration();
        configuration.configure("hibernate.cfg.xml");

        // Step 2: Create SessionFactory
        SessionFactory sessionFactory = configuration.buildSessionFactory();

        Session session = null;
        Transaction transaction = null;

        try {
            // Step 3: Open Session
            session = sessionFactory.openSession();

            // Step 4: Begin Transaction
            transaction = session.beginTransaction();

            // Step 5: Create operational object
            Employee employee = new Employee("Jane", "Doe", "jane.doe@javatbrains.com");

            // Step 6: Save object
            session.persist(employee);

            // Step 7: Commit transaction
            transaction.commit();
            System.out.println("Employee saved successfully: " + employee);

        } catch (Exception e) {
            if (transaction != null) {
                transaction.rollback();
            }
            e.printStackTrace();
        } finally {
            // Step 8: Close session and session factory
            if (session != null) {
                session.close();
            }
            sessionFactory.close();
        }
    }
}

When deploying this architecture into containerized environments, ensuring matching database drivers and network topologies is critical. For container-specific setups, refer to our guidelines on Dockerizing a Spring Boot Application with MySQL.

Real-World Edge Cases and Mitigation Strategies

Building production software requires anticipating structural failures and runtime exceptions. Consider the following common edge cases when working with Hibernate.

1. Detached Entity Modification Outside Active Transactions

If an entity is loaded inside a session, and that session is closed, the entity enters a detached state. Any modifications made to a detached object will not automatically synchronize with the database unless explicitly reattached using session.merge() within an active transaction.

2. The N+1 Select Problem

When fetching parent entities that contain lazy-loaded collections (such as an Employee possessing a list of Project entities), iterating through the parent list without explicit joins triggers a separate database query for every single parent record. Mitigate this by utilizing explicit JOIN FETCH clauses in HQL or tuning fetching strategies to batch queries.

3. Session Leakage and Connection Pool Exhaustion

Failing to close Hibernate sessions in a finally block or relying entirely on garbage collection leads to unclosed JDBC connections. Under high concurrency, this exhausts the connection pool and halts the application. Always wrap session allocations in try-with-resources blocks or explicit try-catch-finally blocks.

Troubleshooting Common Hibernate Issues

Developers frequently encounter specific error messages during initial setups. Use this quick troubleshooting guide to resolve them:

  • org.hibernate.MappingException: Unknown entity: This indicates that the entity class has not been registered in the hibernate.cfg.xml file via the <mapping class="..."/> tag, or is missing the @Entity annotation.
  • java.lang.NoClassDefFoundError: jakarta/persistence/Entity: This occurs when required JPA API dependencies are absent from the classpath. Ensure your build configuration includes the Jakarta Persistence API library.
  • Communications link failure: This network-level error indicates that the database service is offline, credentials are invalid, or port 3306 is blocked by a firewall. Verify connection strings, database status, and network bindings.

Summary

Hibernate eliminates the tedium of manual JDBC boilerplate management by automating persistence mechanics through Object-Relational Mapping. By carefully managing lifecycle components such as the SessionFactory and short-lived Session instances, developers build maintainable enterprise persistence layers. Structuring entities cleanly, keeping transactions concise, and handling database resource closures correctly ensures high-performance, resilient Java applications.

Comments

Popular posts from this blog

JVM, JRE and JDK in Java

Understanding JVM, JRE, and JDK in Java Every Java developer encounters three fundamental acronyms on their first day: JVM , JRE , and JDK . Misunderstanding these foundational components leads to runtime exceptions, deployment failures, and incorrect build environments. This guide breaks down the precise architectural boundaries, memory structures, and deployment requirements of each component. ▶ Listen English (India) English (US) Hindi Telugu Tamil Kannada Malayalam Bengali Marathi Gujarati Punjabi Urdu Arabic Spanish French German Portuguese Japanese Korean Chinese (Simplified) Pick a language, then press Listen. The core problem this guide solves is ambiguous environment configuration. Developers often attempt to run production applications using a Development Kit when a Runtime Environment suffices, or they deploy platform-incompatible binaries to minimal Li...

Prime, Fibonacci and Factorial number with example in java

Mastering Prime, Fibonacci, and Factorial Algorithms in Java Prime Number Validation Workflow Prime Number Validation Workflow 1 Boundary Check Verify if the input number is less than or equal to 1. 2 Even Number Check Check if divisible by 2 and return true only if number is 2. 3 Square Root Limit Calculate integer square root as the upper loop bound. 4 Odd Factor Loop Iterate through odd integers up to limit checking divisibility. Figure: Prime Number Validation Workflow Technical coding interviews frequently test foundational algorithmic competence through three classic mathematical problems: identifying prime numbers, generating Fibonacci sequences, and calculating factorials. While these concepts originate in basic arithmetic, writing production-grade Java code to solve them requires careful attention to time complexity, memory allocation, boundary conditions, and overflow behavior. This tutorial provides rigorous, optimized Java i...

How to insert images into database using JDBC?

How to Insert Images into a Database Using JDBC Storing binary data such as images, PDFs, and application assets is a frequent requirement in enterprise software engineering. While relational databases like MySQL are optimized for structured tabular text and numeric data, they also provide robust binary storage types—specifically BLOB (Binary Large Object) variants—to handle arbitrary byte streams. When interacting with relational stores through Java, the Java Database Connectivity (JDBC) API serves as the primary bridge. ▶ Listen English (India) English (US) Hindi Telugu Tamil Kannada Malayalam Bengali Marathi Gujarati Punjabi Urdu Arabic Spanish French German Portuguese Japanese Korean Chinese (Simplified) Pick a language, then press Listen. This technical guide demonstrates how to persist image files from a local file system directly into a MySQL database usin...