Skip to content

⚙️ CRUD Like a Rockstar: Build Your First Hibernate App Lightning Fast ⚡

Let’s not sugarcoat it—CRUD operations are the soul of any app. If you can’t create, read, update, or delete records, your app is basically dead on arrival.

Hibernate makes CRUD so easy, it almost feels like cheating.
So today, we’re building a fully working Hibernate CRUD application, with less than 60 lines of code. Yes, seriously.

Let’s roll!


🔥 What You’ll Build Today

You’ll create a simple UserManager app with these features:

✅ Add a new user
✅ Fetch a user by ID
✅ Update user details
✅ Delete a user


📁 Project Structure

If you’ve followed Post 2, you already have:

src/
├── main/
│ ├── java/
│ │ └── com/example/
│ │ ├── User.java
│ │ ├── HibernateUtil.java
│ │ └── UserManager.java ← (This is new!)
│ └── resources/
│ └── hibernate.cfg.xml

👤 Step 1: Your Entity Class (Recap)

package com.example;

import jakarta.persistence.*;

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

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

    public User() {}

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

    // Getters and setters...
}

⚙️ Step 2: Your UserManager Class (CRUD Methods)

package com.example;

import org.hibernate.Session;
import org.hibernate.Transaction;

public class UserManager {

    public static void createUser(String name) {
        User user = new User(name);
        try (Session session = HibernateUtil.getSessionFactory().openSession()) {
            Transaction tx = session.beginTransaction();
            session.save(user);
            tx.commit();
            System.out.println("User created: " + user.getId());
        }
    }

    public static void readUser(int id) {
        try (Session session = HibernateUtil.getSessionFactory().openSession()) {
            User user = session.get(User.class, id);
            if (user != null) {
                System.out.println("User found: " + user.getName());
            } else {
                System.out.println("User not found.");
            }
        }
    }

    public static void updateUser(int id, String newName) {
        try (Session session = HibernateUtil.getSessionFactory().openSession()) {
            Transaction tx = session.beginTransaction();
            User user = session.get(User.class, id);
            if (user != null) {
                user.setName(newName);
                session.update(user);
                tx.commit();
                System.out.println("User updated.");
            } else {
                System.out.println("User not found.");
            }
        }
    }

    public static void deleteUser(int id) {
        try (Session session = HibernateUtil.getSessionFactory().openSession()) {
            Transaction tx = session.beginTransaction();
            User user = session.get(User.class, id);
            if (user != null) {
                session.delete(user);
                tx.commit();
                System.out.println("User deleted.");
            } else {
                System.out.println("User not found.");
            }
        }
    }
}

🚀 Step 3: Test All CRUD Operations

Create a Main.java to call everything:

package com.example;

public class Main {
    public static void main(String[] args) {
        // Create
        UserManager.createUser("Alice");

        // Read
        UserManager.readUser(1);

        // Update
        UserManager.updateUser(1, "Alice Cooper");

        // Delete
        UserManager.deleteUser(1);
    }
}

🧪 Expected Output

User created: 1
User found: Alice
User updated.
User deleted.

ust like that, you’ve built your first Hibernate-powered mini-app 💪


🧠 Recap

In this post, you:

  • Learned to Create, Read, Update, and Delete users using Hibernate
  • Used Session and Transaction objects for managing database operations
  • Avoided a single handwritten SQL query. Hibernate did it all 😎

Leave a Reply

Your email address will not be published. Required fields are marked *