Learnitweb

Introduction to Hibernate Framework

1. Introduction

In this tutorial, we’ll discuss about Hibernate. This tutorial should be considered as an introduction to Hibernate framework. We’ll discuss the problems which Hibernate solves and its capabilities.

Hibernate is an Object/Relational Mapping solution for Java environments. This Object/Relational Mapping refers to the technique of mapping data from an object model representation to a relational data model representation (and vice versa).

Hibernate is the default JPA implementation used by the Spring.

JPA is only a specification and cannot be used on its own, providing only a set of interfaces that define the standard persistence API, which is implemented by a JPA provider, like Hibernate, EclipseLink, or OpenJPA.

2. Architecture

Hibernate architecture

Hibernate sits between the Java application data access layer and the Relational Database and shown in the diagram. Java program uses Hibernate APIs to interact with database and perform operations like get, save, update and delete data.

3. What problems does Hibernate solve?

Following is a typical piece of JDBC code to connect database and get details:

import java.sql.*;

public class FirstExample {
   static final String DB_URL = "dbc:mysql://localhost:3306/mydb";
   static final String USER = "root";
   static final String PASS = "admin";
   static final String QUERY = "SELECT id, first, last, age FROM Employees";

   public static void main(String[] args) {
      // Open a connection
      try(Connection conn = DriverManager.getConnection(DB_URL, USER, PASS);
         Statement stmt = conn.createStatement();
         ResultSet rs = stmt.executeQuery(QUERY);) {
         // Extract data from result set
         while (rs.next()) {
            // Retrieve by column name
            System.out.print("ID: " + rs.getInt("id"));
            System.out.print(", Age: " + rs.getInt("age"));
            System.out.print(", First: " + rs.getString("first"));
            System.out.println(", Last: " + rs.getString("last"));
         }
      } catch (SQLException e) {
         e.printStackTrace();
      } 
   }
} 

If you observe there is code to retrieve data from the table. If required this data can be retrieved and set in an object. If Customer is the class which needs to be populated from the table data, using Hibernate it can be done like this:

List<Customer> customerList = customerRepository.findAll();

Hibernate does all the translation from table data to the object graph.

4. What does Hibernate do?

Following are few capabilities of Hibernate:

  • Hibernate takes care of mapping from Java classes to database tables and vice versa.
  • You can retrieve entities or DTOs, including hierarchical parent-child DTO projections.
  • JDBC batching can be enabled without modifying the data access code.
  • You have support for optimistic locking.
  • Optimistic locking is supported, along with a pessimistic locking abstraction that operates independently of database-specific syntax, allowing you to acquire READ, WRITE, or SKIP LOCKs.
  • Hibernate takes care of mapping Java data types to SQL data types.
  • Hibernate provides data query and retrieval facilities.
  • Hibernate enables you to write native SQL queries as well.
  • Hibernate removes the need to write most of regular boiler-plate code to translate table data to the objects.
  • Hibernate has the facility to manage table mappings which translate to object mappings like one-to-one, one-to-many and so on.
  • Hibernate can automatically generate primary keys.
  • Hibernate framework’s query language (HQL) is independent of database. So you can migrate to new database without re-writing queries.
  • Hibernate supports caching of memory.
  • You have a database-independent pagination API.
  • You have built-in support for audit logging via Hibernate Envers.
  • You have built-in support for multitenancy.

5. Disadvantages of JPA and Hibernate

  • Performance Overhead: Object conversion and lazy loading can lead to inefficiencies (e.g., N+1 queries).
  • Complex Tuning: Proper configuration of caching and query optimization can be challenging.
  • Limited SQL Control: Abstracted SQL may hinder fine-tuning for database-specific optimizations.
  • Learning Curve: Configuration and complex mappings can be difficult for beginners.
  • Relational Database Focus: Limited support for NoSQL or non-relational databases.
  • Slow Startup: Applications may experience slow initialization due to entity class processing.
  • Complex Transaction Handling: Managing complex transactions and concurrency can be error-prone.
  • Database-Specific Features: Advanced DB features may be hard to access via JPA/Hibernate.
  • Limited Support for Complex Use Cases: Handling complex inheritance and bulk operations can be inefficient.
  • Versioning and Compatibility: Upgrading Hibernate/JPA versions can lead to compatibility issues.