Software Training Institute in Chennai with 100% Placements – SLA Institute
⭐ Exclusive Summer Courses Offer ⭐ 💰 Flat ₹5,000 - ₹10,000 off on all courses 👨‍👩‍👧 Additional discounts for group enrollments 🎓 100% Placement Support 🏆 90,000+ Students Successfully Placed 🚀 Avail now! Limited seats only!
Hibernate Tutorial For Beginners - Softlogic Systems
Share on your Social Media

Hibernate Tutorial for beginners

Published On: September 17, 2024

Introduction

Struggling with lengthy JDBC code and manual SQL for database interactions? You’re not alone! Hibernate makes this easier, allowing you to think in terms of Java objects rather than mundane boilerplate. This Hibernate tutorial for beginners is your easy-to-follow guide to learning Object-Relational Mapping (ORM) using Hibernate. Ready to create strong, maintainable Java applications? Read the complete Hibernate course syllabus now!

Why Students or Freshers Learn Hibernate?

Students and freshers ought to learn the Hibernate framework for a number of important reasons:

  • Industry Demand: Hibernate is the most popular Object-Relational Mapping (ORM) tool used in enterprise Java development. Familiarity with it makes a tremendous difference to employability.
  • Makes Database Interaction Easier: It eliminates the necessity to write redundant, error-fraught JDBC code and imperative SQL queries, making application development faster.
  • Concentration on Business Logic: With its mapping from Java objects to database tables, it enables developers to concentrate on the core business logic of the application.
  • Standardized Skill: It relies on the Java Persistence API (JPA) standard, and the skill is transferable to other implementations of JPA.
  • Career Foundation: Learning Hibernate is an essential basis to acquire other sophisticated Java frameworks such as Spring Data JPA.

Check out our Hibernate interview questions and answers to get started.

Check your knowledge level with our smart Knowledge Assessment Tool

  • Instant skill evaluation with accurate scoring
  • Identify strengths and learning gaps easily
  • Designed for students and working professionals
  • Smart assessment to guide your career growth

Take Your Eligibility Report Instantly

Step-by-Step Hibernaate Tutorial for Beginners

This in-depth Hibernate tutorial covers a step-by-step setup of a simple Hibernate project, starting with the “installation” steps (adding dependencies) and ending with basic CRUD (Create, Read, Update, Delete) operations.

Step 1: Project Setup and “Installation” (Maven Dependencies)

Since Hibernate is a framework library, it is not installed as a separate program. You “install” it by adding its <dependencies> to your project build file, usually pom.xml for Maven.

Prerequisites Check
  • Java Development Kit (JDK 17 or above)
  • Maven (or an IDE such as IntelliJ/Eclipse with Maven support)
  • An operational MySQL database instance.
pom.xml Configuration

Initialize a new Maven project and include the following dependencies in the dependencies element of your pom.xml:

<project>

    <properties>

        <maven.compiler.source>17</maven.compiler.source>

        <maven.compiler.target>17</maven.compiler.target>

        <hibernate.version>6.4.4.Final</hibernate.version>

        <mysql.connector.version>8.3.0</mysql.connector.version>

    </properties>

    <dependencies>

        <dependency>

            <groupId>org.hibernate.orm</groupId>

            <artifactId>hibernate-core</artifactId>

            <version>${hibernate.version}</version>

        </dependency>

        <dependency>

            <groupId>mysql</groupId>

            <artifactId>mysql-connector-java</artifactId>

            <version>${mysql.connector.version}</version>

        </dependency>

    </dependencies>

</project>

Action: Save the file. Maven will download the required Hibernate and MySQL JDBC driver JARs automatically, finishing the “installation.”

Step 2: Create the Database Configuration File

Hibernate must learn how to connect to your database. Make the file hibernate.cfg.xml in the src/main/resources directory.

<!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>

        <property name=”hibernate.connection.driver_class”>com.mysql.cj.jdbc.Driver</property>

        <property name=”hibernate.connection.url”>jdbc:mysql://localhost:3306/hibernate_db</property>

        <property name=”hibernate.connection.username”>root</property>

        <property name=”hibernate.connection.password”>your_password</property>

        <property name=”hibernate.dialect”>org.hibernate.dialect.MySQL8Dialect</property>

        <property name=”hibernate.show_sql”>true</property>

        <property name=”hibernate.format_sql”>true</property>

        <property name=”hibernate.hbm2ddl.auto”>update</property>

        <mapping class=”com.example.entity.Student” />

    </session-factory>

</hibernate-configuration>

Action: Substitute jdbc:mysql://localhost:3306/hibernate_db, root, and your_password with your own MySQL database URL, username, and password. Be sure also that the database hibernate_db (or the name of your choice) actually exists on your MySQL server. 

Step 3: Create the Entity Class (Student)

The Entity is a simple Java object (POJO) which maps directly to a database table. We utilize JPA Annotations (which Hibernate implements) to specify this mapping.

Create package com.example.entity and the Student.java class within it.

package com.example.entity;

import jakarta.persistence.*;

@Entity // Marks this class as a persistent entity

@Table(name = “student”) // Maps to the ‘student’ table

public class Student {

    @Id // Primary key

    @GeneratedValue(strategy = GenerationType.IDENTITY) // Auto-incrementing key

    @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;

    // Default constructor is mandatory for Hibernate

    public Student() {}

    // Constructor for creating new objects (without ID)

    public Student(String firstName, String lastName, String email) {

        this.firstName = firstName;

        this.lastName = lastName;

        this.email = email;

    }

    // — Getters and Setters (omitted for brevity) —

    @Override

    public String toString() {

        return “Student [id=” + id + “, firstName=” + firstName + “, lastName=” + lastName + “, email=” + email + “]”;

    }

}

Step 4: Create the SessionFactory Utility

SessionFactory is a thread-safe, expensive-to-create object which must only be created once for an application. It reads configuration and coordinates database connections.

Create a package com.example.util and the HibernateUtil.java class.

package com.example.util;

import org.hibernate.SessionFactory;

import org.hibernate.cfg.Configuration;

import com.example.entity.Student;

public class HibernateUtil {

    private static final SessionFactory sessionFactory = buildSessionFactory();

    private static SessionFactory buildSessionFactory() {

        try {

            // Create the SessionFactory from hibernate.cfg.xml and the Student entity

            return new Configuration()

                    .configure(“hibernate.cfg.xml”)

                    .addAnnotatedClass(Student.class) // Explicitly add the entity class

                    .buildSessionFactory();

        } catch (Throwable ex) {

            System.err.println(“Initial SessionFactory creation failed.” + ex);

            throw new ExceptionInInitializerError(ex);

        }

    }

    public static SessionFactory getSessionFactory() {

        return sessionFactory;

    }

    public static void shutdown() {

        // Closes connection pool and caches

        getSessionFactory().close();

    }

}

Step 5: CRUD Operations (DAO)

The Session object is the main interface used by Hibernate for operations, and it signifies one unit of work. All write operations to the database have to be done within a Transaction.

Create a package com.example.dao and the StudentDAO.java class.

5.1 Create (Save)

package com.example.dao;

import org.hibernate.Session;

import org.hibernate.Transaction;

import com.example.entity.Student;

import com.example.util.HibernateUtil;

import java.util.List;

public class StudentDAO {

    public void saveStudent(Student student) {

        Transaction transaction = null;

        try (Session session = HibernateUtil.getSessionFactory().openSession()) {

            transaction = session.beginTransaction();

            session.persist(student); // Saves the new entity

            transaction.commit();

        } catch (Exception e) {

            if (transaction != null) {

                transaction.rollback();

            }

            e.printStackTrace();

        }

    }

    // … rest of CRUD methods below

// …

5.2 Read (Get by ID and Get All)

// Read by Primary Key

    public Student getStudent(int id) {

        try (Session session = HibernateUtil.getSessionFactory().openSession()) {

            // session.get() retrieves the entity by ID

            return session.get(Student.class, id);

        } catch (Exception e) {

            e.printStackTrace();

            return null;

        }

    }

    // Read All using HQL/JPQL

    public List<Student> getAllStudents() {

        try (Session session = HibernateUtil.getSessionFactory().openSession()) {

            // “from Student” is Hibernate Query Language (HQL) or JPQL, operating on the Entity name

            return session.createQuery(“from Student”, Student.class).list();

        } catch (Exception e) {

            e.printStackTrace();

            return null;

        }

    }

5.3 Update

public void updateStudent(Student student) {

        Transaction transaction = null;

        try (Session session = HibernateUtil.getSessionFactory().openSession()) {

            transaction = session.beginTransaction();

            session.merge(student); // Updates the entity in the database

            transaction.commit();

        } catch (Exception e) {

            if (transaction != null) {

                transaction.rollback();

            }

            e.printStackTrace();

        }

    }

// …

5.4 Delete

public void deleteStudent(int id) {

        Transaction transaction = null;

        try (Session session = HibernateUtil.getSessionFactory().openSession()) {

            transaction = session.beginTransaction();

            Student student = session.get(Student.class, id);

            if (student != null) {

                session.remove(student); // Deletes the entity

                System.out.println(“Student with ID: ” + id + ” is deleted.”);

            }

            transaction.commit();

        } catch (Exception e) {

            if (transaction != null) {

                transaction.rollback();

            }

            e.printStackTrace();

        }

    }

}

Step 6: Testing the Application (App.java)

Test the entire flow of data interaction in your main class.

package com.example;

import com.example.dao.StudentDAO;

import com.example.entity.Student;

import com.example.util.HibernateUtil;

import java.util.List;

public class App {

    public static void main(String[] args) {

        StudentDAO studentDAO = new StudentDAO();

        // 1. CREATE

        System.out.println(“\n— 1. Creating a student —“);

        Student newStudent = new Student(“Harry”, “Potter”, “harry@hogwarts.edu”);

        studentDAO.saveStudent(newStudent);

        System.out.println(“Saved student (ID should be > 0): ” + newStudent.getId());

        // 2. READ (by ID)

        System.out.println(“\n— 2. Retrieving student —“);

        Student retrievedStudent = studentDAO.getStudent(newStudent.getId());

        System.out.println(“Retrieved: ” + retrievedStudent);

        // 3. UPDATE

        System.out.println(“\n— 3. Updating student email —“);

        retrievedStudent.setEmail(“theboywholived@hogwarts.edu”);

        studentDAO.updateStudent(retrievedStudent);

        System.out.println(“Updated: ” + studentDAO.getStudent(newStudent.getId()));

        // 4. READ (All)

        System.out.println(“\n— 4. Retrieving all students —“);

        List<Student> students = studentDAO.getAllStudents();

        students.forEach(s -> System.out.println(“All: ” + s));

        // 5. DELETE

        System.out.println(“\n— 5. Deleting student —“);

        studentDAO.deleteStudent(newStudent.getId());

        // Final shutdown

        HibernateUtil.shutdown();

    }

}

By running this App.java file, you will see the SQL queries printed to the console (because of hibernate.show_sql=true) and the related data updates in your MySQL database, successfully proving your first operational Hibernate ORM application! Learn further with our Hibernate challenges and solutions for beginners

Real Time Examples for Hibernate Tutorial for Learners

Here are some real-time examples for Hibernate tutorial for learners:

E-commerce Product Catalog Management

Problem: Storing thousands of products, categories, and inventory levels involves complex SQL joins and hand-written result set processing with plain JDBC.

Hibernate Solution: You specify Product and Category as Java classes. Hibernate performs the one-to-many relationship mapping (e.g., a Category has multiple Products) automatically. You can retrieve a product and a category by simply invoking a getter method (product.getCategory()), avoiding cumbersome SQL.

Social Media User Profile & Feed

Problem: A User object interacts with a Post object, and a Post object contains several Comment objects. It’s error-prone to control transactions (e.g., saving a new post) manually across three interlinked tables.

Hibernate Solution: The Session of Hibernate controls the transaction scope. You save the Post object, and if you have cascading set up, the dependent Comment objects are persisted or updated automatically in the database without individual SQL inserts. This provides data consistency (ACID properties).

Hospital Management System (Data Validation)

Problem: Business rules need to be applied (e.g., Patient.age should be $>0$) prior to saving a Patient record. With JDBC, you validate the object first, then build the SQL.

Hibernate Solution: Hibernate has built-in support for JPA callback methods and works well with validation frameworks (such as Bean Validation). You can directly put constraints on your Java fields (@Min(0) on the age property). Hibernate makes sure that bad Java objects are never saved to the database.

Ready to put your knowledge to practice? Have a look at these hands-on Hibernate project ideas to create your portfolio!

FAQs About Hibernate Tutorial for Beginners

1. What is the Hibernate framework?

Hibernate is an Object-Relational Mapping (ORM) tool for Java. It makes database access easier by mapping Java objects (entities) to database tables directly, without hiding low-level, complex JDBC and manual SQL code. It is the most widely used implementation of the JPA specification.

2. Why is Hibernate used?

It significantly minimizes boilerplate code, speeds up development, and enhances application maintainability. Hibernate manages persistence, transactional integrity, caching, and data retrieval so that developers can concentrate simply on the object-oriented business logic instead of SQL and result set parsing.

3. What is basics of Hibernate?

The fundamentals entail mapping a POJO (Plain Old Java Object) to a database table through JPA annotations (@Entity, @Id). Core pieces are the SessionFactory (connection manager), Session (unit of work), and Transaction (maintaining data integrity for CUD operations).

4. Is Hibernate a backend framework?

Yes, Hibernate is essentially a backend framework. It runs completely on the server side (backend) to handle the persistence layer, which means interacting with the database. It’s usually part of larger backend frameworks like Spring.

5. Is Hibernate only for Java?

Although initially created for Java and most commonly used in the Java universe, Hibernate does have components such as Hibernate Shards and Hibernate OGM. Nevertheless, its main ORM product is Java and JVM environment bound.

6. Is Hibernate still used in 2025?

Yes, Hibernate is very much applicable and in great demand, particularly when coupled with the Spring Framework through Spring Data JPA. It’s a standard data persistence technology of the industry for enterprise Java applications, showing great performance and constant updates. Explore the salary scope for Hibernate skilled Java developers.

7. Which is better, JDBC or Hibernate?

Hibernate is usually superior to most enterprise applications since it increases productivity and keeps clean, object-oriented code. JDBC provides more low-level control and unadulterated performance for highly optimized, very complex queries at the expense of writing a lot more, more unmanageable code.

8. Is Hibernate a tool or technology?

Hibernate is a technology/framework. A tool usually has a precise, single task (such as a code formatter), while a framework, like Hibernate, offers a reusable, end-to-end structure and set of APIs to construct the entire persistence layer of an application.

9. Does Hibernate use SQL?

Yes, Hibernate does use SQL internally. It generates the respective, optimized SQL statements (SELECT, INSERT, UPDATE, DELETE) automatically depending on the developer’s usage of HQL/JPQL (Hibernate/Java Persistence Query Language) or Criteria API calls. The developer hardly ever writes raw SQL.

10. Which companies use Hibernate?

A multitude of international businesses employ Hibernate. Prominent examples are large tech corporations and financial institutions such as IBM, Oracle, Dell, Capgemini, and Bank of America. Being a part of the omnipresent Spring Framework makes it a staple of global enterprise application development.

Conclusion

You now know how to configure a project, map Java entities to a database with JPA annotations, and execute key CRUD operations without coding manual JDBC or too much SQL. This potent ORM technique is the building block for developing modern, scalable Java applications. Ready to learn advanced topics such as Caching, Relationships, and HQL optimization? Take the complete Hibernate course in Chennai today!

Share on your Social Media
Get Your Instant Job & Placement Eligibility
Report in Just 30 Seconds!
Below 30% - not Eligible (Needs Preparation)
30% – 70% - Partially Eligible (Needs Guidance)
Above 70% - Fully Eligible (Ready to Start)

We are excited to get started with you

Give us your information and we will arange for a free call (at your convenience) with one of our counsellors. You can get all your queries answered before deciding to join SLA and move your career forward.