S01L09 – Hibernate CURD operation – Read


Hibernate CRUD Operation – Read

Table of Contents

  1. Introduction
  2. Understanding Hibernate CRUD Operations
  3. Read Operation in Hibernate
  4. Code Walkthrough
  5. Comparison Table
  6. Conclusion

Introduction

Hibernate is a powerful ORM (Object-Relational Mapping) framework that simplifies database interactions in Java. CRUD operations—Create, Read, Update, and Delete—are fundamental in any database-driven application.

This article focuses on “Read Operation” in Hibernate, explaining its significance, syntax, and implementation using a step-by-step approach.

Operation Purpose Description
Create (C) Add new records Inserts data into the database
Read (R) Fetch existing records Retrieves data using unique identifiers
Update (U) Modify existing records Updates specified records in the database
Delete (D) Remove existing records Deletes specified records from the database

Understanding Hibernate CRUD Operations

What is CRUD?

CRUD refers to the four basic database operations—Create, Read, Update, and Delete—performed on persistent data in any application.

Hibernate’s Role

Hibernate provides a simplified approach to handle CRUD operations by abstracting JDBC code and managing database entities through mapping.

Read Operation in Hibernate

The Read Operation in Hibernate involves retrieving data using the primary key or custom queries. Hibernate simplifies fetching records with minimal code.

Steps to Perform a Read Operation

  1. Create a SessionFactory.
  2. Open a Session.
  3. Begin a Transaction.
  4. Fetch the Entity using session.get() method.
  5. Commit the Transaction.

Code Implementation

Entity Class – Users.java

Main Program – App.java

Code Walkthrough

  • Entity Class: Maps Java class to the database table.
  • Main Class: Retrieves a record using the primary key with session.get().

Output

Comparison Table

Method Purpose Returns
session.get() Fetch data by Primary Key Entity object or null if not found
session.load() Fetch data lazily by Proxy Proxy object; exception if not found

Conclusion

The Read Operation in Hibernate simplifies retrieving records from the database. By leveraging methods like session.get(), developers can fetch specific entities with minimal effort.