Skip to content

Basic CRUD Operations in Hibernate

So, what’s CRUD? It’s not a new type of sandwich, don’t worry. CRUD stands for Create, Read, Update, and Delete – the four fundamental actions you can perform on any database.

Now, enter Hibernate, your database's best friend. It’s like the organizer of your data world, helping you handle these CRUD operations with ease. Imagine it as your personal assistant, ready to fetch, update, add, or remove data from your database whenever you need it.

CRUD Operations

Employee Class:

java
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;

@Entity
public class Employee {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private int id;
    private String name;
    private String department;
    private double salary;

    // Constructors, getters, and setters
    public Employee() {
    }

    public Employee(String name, String department, double salary) {
        this.name = name;
        this.department = department;
        this.salary = salary;
    }

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

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

    public String getName() {
        return name;
    }

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

    public String getDepartment() {
        return department;
    }

    public void setDepartment(String department) {
        this.department = department;
    }

    public double getSalary() {
        return salary;
    }

    public void setSalary(double salary) {
        this.salary = salary;
    }
}

HibernateUtil Class:

java
import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistry;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;

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

    private static SessionFactory buildSessionFactory() {
        try {
            // Create the SessionFactory from hibernate.cfg.xml
            Configuration configuration = new Configuration().configure();
            StandardServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder()
                    .applySettings(configuration.getProperties()).build();
            return configuration.buildSessionFactory(serviceRegistry);
        } catch (Throwable ex) {
            // Make sure you log the exception, as it might be swallowed
            System.err.println("Initial SessionFactory creation failed." + ex);
            throw new ExceptionInInitializerError(ex);
        }
    }

    public static SessionFactory getSessionFactory() {
        return sessionFactory;
    }

    public static void shutdown() {
        // Close caches and connection pools
        getSessionFactory().close();
    }
}

You have the Employee class representing your entity and the HibernateUtil class providing the session factory for Hibernate operations.

1. Create (C) Operation

Creating new data entries in your database is the first step in CRUD operations. Here's how you can do it using Hibernate:

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

public class Main {
    public static void main(String[] args) {
        // Initialize Hibernate session
        Session session = HibernateUtil.getSessionFactory().openSession();
        Transaction transaction = null;

        try {
            transaction = session.beginTransaction();

            // Create a new instance of your entity class
            Employee employee = new Employee();
            employee.setName("John Doe");
            employee.setDepartment("IT");
            employee.setSalary(50000);

            // Save the new entry to the database
            session.save(employee);

            transaction.commit();
        } catch (Exception e) {
            if (transaction != null) {
                transaction.rollback();
            }
            e.printStackTrace();
        } finally {
            session.close();
        }
    }
}

In this example, we're creating a new Employee object and saving it to the database using Hibernate's session.save() method.

2. Read (R) Operation

Reading data from the database is essential for retrieving information. Here's how you can do it using Hibernate:

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

public class Main {
    public static void main(String[] args) {
        // Initialize Hibernate session
        Session session = HibernateUtil.getSessionFactory().openSession();
        Transaction transaction = null;

        try {
            transaction = session.beginTransaction();

            // Retrieve an employee by ID
            Employee employee = session.get(Employee.class, 1);

            System.out.println("Employee Name: " + employee.getName());
            System.out.println("Employee Department: " + employee.getDepartment());
            System.out.println("Employee Salary: " + employee.getSalary());

            transaction.commit();
        } catch (Exception e) {
            if (transaction != null) {
                transaction.rollback();
            }
            e.printStackTrace();
        } finally {
            session.close();
        }
    }
}

In this example, we're using Hibernate's session.get() method to retrieve an Employee object by its ID from the database.

3. Update (U) Operation

Updating existing data entries allows you to modify information in the database. Here's how you can do it using Hibernate:

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

public class Main {
    public static void main(String[] args) {
        // Initialize Hibernate session
        Session session = HibernateUtil.getSessionFactory().openSession();
        Transaction transaction = null;

        try {
            transaction = session.beginTransaction();

            // Retrieve an employee by ID
            Employee employee = session.get(Employee.class, 1);

            // Update employee's salary
            employee.setSalary(60000);

            // Save the updated entry to the database
            session.update(employee);

            transaction.commit();
        } catch (Exception e) {
            if (transaction != null) {
                transaction.rollback();
            }
            e.printStackTrace();
        } finally {
            session.close();
        }
    }
}

In this example, we're retrieving an Employee object by its ID, updating its salary, and then saving the changes to the database using Hibernate's session.update() method.

4. Delete (D) Operation

Deleting data entries removes unwanted information from the database. Here's how you can do it using Hibernate:

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

public class Main {
    public static void main(String[] args) {
        // Initialize Hibernate session
        Session session = HibernateUtil.getSessionFactory().openSession();
        Transaction transaction = null;

        try {
            transaction = session.beginTransaction();

            // Retrieve an employee by ID
            Employee employee = session.get(Employee.class, 1);

            // Delete the employee
            session.delete(employee);

            transaction.commit();
        } catch (Exception e) {
            if (transaction != null) {
                transaction.rollback();
            }
            e.printStackTrace();
        } finally {
            session.close();
        }
    }
}

In this example, we're retrieving an Employee object by its ID and then deleting it from the database using Hibernate's session.delete() method.

Waytojava is designed to make learning easier. We simplify examples for better understanding. We regularly check tutorials, references, and examples to correct errors, but it's important to remember that humans can make mistakes.