Hibernate CRUD Operations Example

In this step-by-step tutorial, we will create a simple Hibernate application to perform CRUD (Create, Read, Update, Delete) operations on a User entity using Hibernate 6+ and a MySQL database. We will also create a separate UserDao class for CRUD operations.

Prerequisites

  1. Java Development Kit (JDK) 17 or later
  2. MySQL Database
  3. Maven (for project management and build)
  4. Integrated Development Environment (IDE) like Eclipse or IntelliJ IDEA

Step 1: Set Up Maven Project

Create a Maven project in your IDE and add the following dependencies in the pom.xml file:

<dependencies>
    <dependency>
        <groupId>org.hibernate.orm</groupId>
        <artifactId>hibernate-core</artifactId>
        <version>6.4.0.Final</version>
    </dependency>
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>8.0.32</version>
    </dependency>
    <dependency>
        <groupId>jakarta.persistence</groupId>
        <artifactId>jakarta.persistence-api</artifactId>
        <version>3.0.0</version>
    </dependency>
</dependencies>

Step 2: Configure Hibernate

Create a hibernate.cfg.xml file under the src/main/resources directory to configure Hibernate settings:

<!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?useSSL=false</property>
        <property name="hibernate.connection.username">root</property>
        <property name="hibernate.connection.password">root</property>
        <property name="hibernate.dialect">org.hibernate.dialect.MySQL8Dialect</property>
        <property name="hibernate.show_sql">true</property>
        <property name="hibernate.hbm2ddl.auto">update</property>
        <mapping class="com.example.entity.User"/>
    </session-factory>
</hibernate-configuration>

Step 3: Create User Entity

Create a User entity class to represent a user in the database:

package com.example.entity;

import jakarta.persistence.*;

@Entity
@Table(name = "user")
public class User {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

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

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

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

    // Constructors, getters, setters, and toString() method
    public User() {}

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

    public Long getId() {
        return id;
    }

    public void setId(Long 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 "User [id=" + id + ", firstName=" + firstName + ", lastName=" + lastName + ", email=" + email + "]";
    }
}

Entity Mapping Diagram

+-------------------+
|      User         |
+-------------------+
| id (PK)           |
| first_name        |
| last_name         |
| email             |
+-------------------+

Step 4: Create Hibernate Utility Class

Create a utility class to manage Hibernate sessions:

package com.example.util;

import org.hibernate.SessionFactory;
import org.hibernate.boot.Metadata;
import org.hibernate.boot.MetadataSources;
import org.hibernate.boot.registry.StandardServiceRegistry;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;

public class HibernateUtil {
    private static StandardServiceRegistry registry;
    private static SessionFactory sessionFactory;

    public static SessionFactory getSessionFactory() {
        if (sessionFactory == null) {
            try {
                registry = new StandardServiceRegistryBuilder().configure().build();
                MetadataSources sources = new MetadataSources(registry);
                Metadata metadata = sources.getMetadataBuilder().build();
                sessionFactory = metadata.getSessionFactoryBuilder().build();
            } catch (Exception e) {
                e.printStackTrace();
                if (registry != null) {
                    StandardServiceRegistryBuilder.destroy(registry);
                }
            }
        }
        return sessionFactory;
    }

    public static void shutdown() {
        if (registry != null) {
            StandardServiceRegistryBuilder.destroy(registry);
        }
    }
}

Step 5: Create UserDao Class for CRUD Operations

Create a UserDao class to handle CRUD operations on the User entity:

package com.example.dao;

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

import java.util.List;

public class UserDao {

    public void saveUser(User user) {
        Transaction transaction = null;
        try (Session session = HibernateUtil.getSessionFactory().openSession()) {
            transaction = session.beginTransaction();
            session.save(user);
            transaction.commit();
        } catch (Exception e) {
            if (transaction != null) {
                transaction.rollback();
            }
            e.printStackTrace();
        }
    }

    public List<User> getUsers() {
        try (Session session = HibernateUtil.getSessionFactory().openSession()) {
            return session.createQuery("FROM User", User.class).list();
        }
    }

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

    public void deleteUser(Long userId) {
        Transaction transaction = null;
        try (Session session = HibernateUtil.getSessionFactory().openSession()) {
            transaction = session.beginTransaction();
            User user = session.get(User.class, userId);
            if (user != null) {
                session.delete(user);
            }
            transaction.commit();
        } catch (Exception e) {
            if (transaction != null) {
                transaction.rollback();
            }
            e.printStackTrace();
        }
    }
}

Step 6: Implement the Main Class

Create a main class to test the CRUD operations using the UserDao class:

package com.example;

import com.example.dao.UserDao;
import com.example.entity.User;
import com.example.util.HibernateUtil;

import java.util.List;

public class HibernateCRUDExample {

    public static void main(String[] args) {
        UserDao userDao = new UserDao();

        // Create
        userDao.saveUser(new User("Ramesh", "Fadatare", "ramesh.fadatare@example.com"));
        userDao.saveUser(new User("Suresh", "Kumar", "suresh.kumar@example.com"));

        // Read
        List<User> users = userDao.getUsers();
        users.forEach(System.out::println);

        // Update
        User user = users.get(0);
        user.setFirstName("Rameshwar");
        userDao.updateUser(user);

        // Delete
        userDao.deleteUser(user.getId());

        // Read
        users = userDao.getUsers();
        users.forEach(System.out::println);

        // Shutdown Hibernate
        HibernateUtil.shutdown();
    }
}

Explanation of Each Step

  1. Create User Entity: The User entity represents a table in the database with fields id, first_name, last_name, and email.
  2. Configure Hibernate: The hibernate.cfg.xml file configures Hibernate to connect to the MySQL database and maps the User entity.
  3. Hibernate Utility Class: The HibernateUtil class manages the Hibernate SessionFactory and provides a method to shut it down.
  4. UserDao Class: The UserDao class contains methods for CRUD operations (saveUser, getUsers, updateUser, deleteUser) using Hibernate sessions.
  5. Main Class: The HibernateCRUDExample class demonstrates how to use the UserDao class to perform CRUD operations and displays the results.

Summary

This tutorial provided a comprehensive step-by-step guide to setting up Hibernate 6.4, configuring it with a MySQL database, creating a User entity, and performing CRUD operations using a separate UserDao class. By following these steps, you can effectively manage and manipulate database records using Hibernate in a Java application with clear separation of concerns.

Comments

  1. i had read somewhere, only one SessionFactory must be use for only one app

    ReplyDelete
    Replies
    1. because SessionFactory is a expensive process but in your code, you create a new SessionFactory each time you perfrom a CRUD method

      Delete
    2. HibernateUtil is singleton class and returns single SessionFactory instance. Even Hibernate won't allow to create multiple SessionFactory objects for single database. Check the complete example, understand and then comment.

      Delete

Post a Comment

Leave Comment