Hibernate ORM Framework Tutorial

This tutorial will guide you through setting up and using the Hibernate ORM framework with a MySQL database. We will demonstrate how to configure Hibernate, create an entity class (Student), and perform basic CRUD operations using DAO classes.

Introduction

Hibernate is an object-relational mapping (ORM) tool for Java that provides a framework for mapping an object-oriented domain model to a relational database. This tutorial will show you how to set up Hibernate ORM with a MySQL database, create an entity class, and perform basic CRUD operations.

In this tutorial, we will:

  1. Set up a Maven project with necessary dependencies.
  2. Configure Hibernate to connect to MySQL.
  3. Create an entity class (Student).
  4. Perform basic CRUD operations using Hibernate and DAO classes.

Step 1: Set Up Your Project

1.1 Create a Maven Project

Open your IDE and create a new Maven project.

1.2 Add Dependencies

Update your pom.xml file to include dependencies for Hibernate and MySQL.

<project xmlns="http://maven.apache.org/POM/4.0.0"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.example</groupId>
    <artifactId>hibernate-orm-example</artifactId>
    <version>1.0-SNAPSHOT</version>

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

        <!-- MySQL Connector -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.29</version>
        </dependency>

        <!-- SLF4J for logging -->
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
            <version>1.7.32</version>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-simple</artifactId>
            <version>1.7.32</version>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.10.1</version>
                <configuration>
                    <source>21</source>
                    <target>21</target>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>

Step 2: Configure Hibernate

2.1 Create hibernate.cfg.xml

Create a hibernate.cfg.xml file in the src/main/resources directory to configure database connection settings and Hibernate properties.

<!DOCTYPE hibernate-configuration PUBLIC
    "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
    "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">

<hibernate-configuration>
    <session-factory>
        <!-- JDBC Database connection settings -->
        <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">password</property>

        <!-- JDBC connection pool settings -->
        <property name="hibernate.c3p0.min_size">5</property>
        <property name="hibernate.c3p0.max_size">20</property>
        <property name="hibernate.c3p0.timeout">300</property>
        <property name="hibernate.c3p0.max_statements">50</property>
        <property name="hibernate.c3p0.idle_test_period">3000</property>

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

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

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

        <!-- Entities -->
        <mapping class="com.example.entity.Student"/>
    </session-factory>
</hibernate-configuration>

Replace hibernate_db, root, and password with your MySQL database name and credentials.

Explanation:

  • hibernate.connection.driver_class specifies the JDBC driver class for MySQL.
  • hibernate.connection.url specifies the JDBC URL for the database connection.
  • hibernate.connection.username and hibernate.connection.password specify the database credentials.
  • hibernate.c3p0 properties configure the connection pool settings using C3P0.
  • hibernate.dialect specifies the SQL dialect to be used.
  • hibernate.show_sql and hibernate.format_sql properties are used to display and format the generated SQL statements.
  • hibernate.hbm2ddl.auto specifies the schema generation strategy.
  • The <mapping class="com.example.entity.Student"/> line maps the Student entity to the database.

Step 3: Create the Entity Class

Create an entity class Student that will be mapped to a table in the database. This class uses annotations to define the entity and its fields.

package com.example.entity;

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

@Entity
public class Student {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String name;
    private String email;

    // Getters and setters
    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getEmail() {
        return email;
    }

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

Explanation:

  • The @Entity annotation specifies that the class is an entity and is mapped to a database table.
  • The @Id annotation specifies the primary key of the entity.
  • The @GeneratedValue(strategy = GenerationType.IDENTITY) annotation specifies that the primary key is auto-incremented.

Step 4: Create the DAO Class

Create a DAO class to manage database operations using Hibernate.

4.1 Create StudentDAO

package com.example.dao;

import com.example.entity.Student;
import com.example.util.HibernateUtil;
import org.hibernate.Session;
import org.hibernate.Transaction;

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.save(student);
            transaction.commit();
        } catch (Exception e) {
            if (transaction != null) {
                transaction.rollback();
            }
            e.printStackTrace();
        }
    }

    public void updateStudent(Student student) {
        Transaction transaction = null;
        try (Session session = HibernateUtil.getSessionFactory().openSession()) {
            transaction = session.beginTransaction();
            session.update(student);
            transaction.commit();
        } catch (Exception e) {
            if (transaction != null) {
                transaction.rollback();
            }
            e.printStackTrace();
        }
    }

    public Student getStudentById(Long id) {
        try (Session session = HibernateUtil.getSessionFactory().openSession()) {
            return session.get(Student.class, id);
        }
    }

    public List<Student> getAllStudents() {
        try (Session session = HibernateUtil.getSessionFactory().openSession()) {
            return session.createQuery("from Student", Student.class).list();
        }
    }

    public void deleteStudent(Long id) {
        Transaction transaction = null;
        try (Session session = HibernateUtil.getSessionFactory().openSession()) {
            transaction = session.beginTransaction();
            Student student = session.get(Student.class, id);
            if (student != null) {
                session.delete(student);
                System.out.println("Student is deleted");
            }
            transaction.commit();
        } catch (Exception e) {
            if (transaction != null) {
                transaction.rollback();
            }
            e.printStackTrace();
        }
    }
}

Explanation:

  • The StudentDAO class contains methods to interact with the database using Hibernate.
  • The saveStudent method saves a new student to the database.
  • The updateStudent method updates an existing student in the database.
  • The getStudentById method retrieves a student by its ID.
  • The getAllStudents method retrieves all students from the database.
  • The deleteStudent method deletes a student by its ID.

Step 5: Demonstrate CRUD Operations

Create a main class to demonstrate the CRUD operations using the Student entity and StudentDAO class.

5.1 Create MainApp

package com.example.main;

import com.example.dao.StudentDAO

;
import com.example.entity.Student;
import com.example.util.HibernateUtil;

import java.util.List;

public class MainApp {
    public static void main(String[] args) {
        StudentDAO studentDAO = new StudentDAO();

        // Create new students
        Student student1 = new Student();
        student1.setName("Amit Sharma");
        student1.setEmail("amit.sharma@example.com");

        Student student2 = new Student();
        student2.setName("Priya Singh");
        student2.setEmail("priya.singh@example.com");

        // Save students
        studentDAO.saveStudent(student1);
        studentDAO.saveStudent(student2);

        // Update student
        student1.setEmail("amit.sharma_updated@example.com");
        studentDAO.updateStudent(student1);

        // Get student by ID
        Student retrievedStudent = studentDAO.getStudentById(student1.getId());
        System.out.println("Retrieved Student: " + retrievedStudent.getName() + " - " + retrievedStudent.getEmail());

        // Get all students
        List<Student> students = studentDAO.getAllStudents();
        System.out.println("All Students:");
        students.forEach(student -> System.out.println(student.getName() + " - " + student.getEmail()));

        // Delete student
        studentDAO.deleteStudent(student2.getId());

        // Get all students after deletion
        students = studentDAO.getAllStudents();
        System.out.println("All Students after deletion:");
        students.forEach(student -> System.out.println(student.getName() + " - " + student.getEmail()));

        // Shut down the SessionFactory
        HibernateUtil.shutdown();
    }
}

Explanation:

  • The MainApp class demonstrates CRUD operations using the StudentDAO class.
  • The saveStudent method is called to save new students to the database.
  • The updateStudent method is called to update an existing student.
  • The getStudentById method is called to retrieve a student by its ID.
  • The getAllStudents method is called to retrieve all students from the database and display them.
  • The deleteStudent method is called to delete a student by its ID.
  • The getAllStudents method is called again to retrieve all students after the deletion.

5.2 Create HibernateUtil Class

Create a utility class HibernateUtil to manage the Hibernate SessionFactory.

package com.example.util;

import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

public class HibernateUtil {
    private static final SessionFactory sessionFactory = buildSessionFactory();

    private static SessionFactory buildSessionFactory() {
        try {
            // Load the configuration and build the SessionFactory
            return new Configuration().configure().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() {
        getSessionFactory().close();
    }
}

Explanation:

  • The HibernateUtil class provides a singleton SessionFactory and a method to shut it down.
  • The buildSessionFactory method loads the Hibernate configuration from hibernate.cfg.xml and builds the SessionFactory.

Step 6: Run the Application

  1. Ensure your MySQL database is running and the connection details in hibernate.cfg.xml are correct.
  2. Run the MainApp class to load the Hibernate configuration, build the SessionFactory, save students, perform CRUD operations, and print the results.

Sample Output

If everything is set up correctly, running the MainApp class should produce output similar to the following:

Retrieved Student: Amit Sharma - amit.sharma_updated@example.com
All Students:
Amit Sharma - amit.sharma_updated@example.com
Priya Singh - priya.singh@example.com
Student is deleted
All Students after deletion:
Amit Sharma - amit.sharma_updated@example.com

Conclusion

In this tutorial, we have successfully demonstrated how to set up Hibernate ORM framework with Maven, configure it to connect to a MySQL database, create an entity class, and perform basic CRUD operations using Hibernate and DAO classes. This guide provides a solid foundation for using Hibernate with a MySQL database in your applications.


Comments