DEV Community

DevCorner2
DevCorner2

Posted on

🧱 Full Guide: CRUD Operations in Java using Hibernate ORM

Great! Let’s now do a full structured blog-style guide for performing CRUD operations in Java using Hibernate ORM.

Hibernate is a powerful, high-performance ORM (Object-Relational Mapping) framework that helps you **map Java objects to ## πŸ“š What You’ll Learn

  • Setup Hibernate in a Java project
  • Map a Java class to a database table
  • Perform CRUD (Create, Read, Update, Delete) operations
  • Best practices and structure

πŸ“ Prerequisites

  • JDK installed
  • MySQL (or any relational database)
  • Hibernate 5.x or 6.x JARs or Maven
  • IDE (IntelliJ, Eclipse, etc.)

πŸ”§ Project Structure

src/
β”œβ”€β”€ com.example.hibernate/
β”‚   β”œβ”€β”€ model/
β”‚   β”‚   └── User.java
β”‚   β”œβ”€β”€ dao/
β”‚   β”‚   └── UserDAO.java
β”‚   β”œβ”€β”€ util/
β”‚   β”‚   └── HibernateUtil.java
β”‚   └── Main.java
└── hibernate.cfg.xml
Enter fullscreen mode Exit fullscreen mode

1️⃣ hibernate.cfg.xml (Hibernate Configuration)

<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 5.3//EN"
"http://hibernate.org/dtd/hibernate-configuration-5.3.dtd">

<hibernate-configuration>
    <session-factory>
        <!-- Database connection -->
        <property name="hibernate.connection.driver_class">com.mysql.cj.jdbc.Driver</property>
        <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/your_database</property>
        <property name="hibernate.connection.username">root</property>
        <property name="hibernate.connection.password">your_password</property>

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

        <!-- Hibernate settings -->
        <property name="hibernate.hbm2ddl.auto">update</property> <!-- or create, validate, none -->
        <property name="hibernate.show_sql">true</property>

        <!-- Mapped Entity -->
        <mapping class="com.example.hibernate.model.User"/>
    </session-factory>
</hibernate-configuration>
Enter fullscreen mode Exit fullscreen mode

2️⃣ User.java (Entity Class)

package com.example.hibernate.model;

import jakarta.persistence.*;

@Entity
@Table(name = "users")
public class User {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private int id;

    @Column(nullable = false)
    private String name;

    @Column(unique = true, nullable = false)
    private String email;

    public User() {}

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

    // Getters and setters
    // ...
}
Enter fullscreen mode Exit fullscreen mode

3️⃣ HibernateUtil.java (Utility Class)

package com.example.hibernate.util;

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

public class HibernateUtil {
    private static final SessionFactory sessionFactory;

    static {
        try {
            sessionFactory = new Configuration().configure().buildSessionFactory();
        } catch (Throwable ex) {
            System.err.println("SessionFactory creation failed." + ex);
            throw new ExceptionInInitializerError(ex);
        }
    }

    public static SessionFactory getSessionFactory() {
        return sessionFactory;
    }
}
Enter fullscreen mode Exit fullscreen mode

4️⃣ UserDAO.java (Data Access Object)

package com.example.hibernate.dao;

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

import java.util.List;

public class UserDAO {

    // Create
    public void saveUser(User user) {
        Transaction tx = null;
        try (Session session = HibernateUtil.getSessionFactory().openSession()) {
            tx = session.beginTransaction();
            session.save(user);
            tx.commit();
            System.out.println("User saved successfully.");
        } catch (Exception e) {
            if (tx != null) tx.rollback();
            e.printStackTrace();
        }
    }

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

    // Update
    public void updateUser(User user) {
        Transaction tx = null;
        try (Session session = HibernateUtil.getSessionFactory().openSession()) {
            tx = session.beginTransaction();
            session.update(user);
            tx.commit();
            System.out.println("User updated successfully.");
        } catch (Exception e) {
            if (tx != null) tx.rollback();
            e.printStackTrace();
        }
    }

    // Delete
    public void deleteUser(int userId) {
        Transaction tx = null;
        try (Session session = HibernateUtil.getSessionFactory().openSession()) {
            tx = session.beginTransaction();
            User user = session.get(User.class, userId);
            if (user != null) {
                session.delete(user);
                System.out.println("User deleted successfully.");
            }
            tx.commit();
        } catch (Exception e) {
            if (tx != null) tx.rollback();
            e.printStackTrace();
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

5️⃣ Main.java (Test Your Code)

package com.example.hibernate;

import com.example.hibernate.dao.UserDAO;
import com.example.hibernate.model.User;

import java.util.List;

public class Main {
    public static void main(String[] args) {
        UserDAO dao = new UserDAO();

        // Create
        dao.saveUser(new User("John Doe", "[email protected]"));

        // Read
        List<User> users = dao.getAllUsers();
        users.forEach(u -> System.out.println(u.getId() + ": " + u.getName() + " - " + u.getEmail()));

        // Update
        if (!users.isEmpty()) {
            User u = users.get(0);
            u.setName("Jane Doe");
            dao.updateUser(u);
        }

        // Delete
        if (!users.isEmpty()) {
            dao.deleteUser(users.get(0).getId());
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

πŸ§ͺ Output

Hibernate: insert into users (email, name) values (?, ?)
User saved successfully.
1: John Doe - [email protected]
User updated successfully.
User deleted successfully.
Enter fullscreen mode Exit fullscreen mode

βš™οΈ Maven Dependencies (if using Maven)

<dependencies>
    <dependency>
        <groupId>org.hibernate.orm</groupId>
        <artifactId>hibernate-core</artifactId>
        <version>6.4.4.Final</version>
    </dependency>
    <dependency>
        <groupId>jakarta.persistence</groupId>
        <artifactId>jakarta.persistence-api</artifactId>
        <version>3.1.0</version>
    </dependency>
    <dependency>
        <groupId>com.mysql</groupId>
        <artifactId>mysql-connector-j</artifactId>
        <version>8.0.33</version>
    </dependency>
</dependencies>
Enter fullscreen mode Exit fullscreen mode

🧠 Best Practices

  • Avoid hibernate.hbm2ddl.auto=update in production β€” use migrations (Liquibase/Flyway).
  • Use DAO/Service layers to keep business logic clean.
  • Enable second-level caching for performance in real apps.
  • Use JPA annotations (@Entity, @Table, @Column, etc.) to ensure portability.

Top comments (0)