Hibernate - Create, Read, Update and Delete (CRUD) Operations Example

In this article, we will discuss how to use Hibernate to perform CRUD operations against the MySQL database. In this example, we are using MySQL as a database. A CRUD operation deals with creating, retrieving, updating, and deleting records from the table.

Hibernate is an open-source Object-Relational Mapping (ORM) framework for the Java programming language. It provides a powerful and flexible way to map Java objects to relational database tables and to interact with those tables using object-oriented programming techniques.

Hibernate makes it easier for developers to create database-driven applications by eliminating much of the need for low-level SQL programming. Instead, developers can work with high-level Java objects, and let Hibernate handle the details of mapping those objects to the database.

Hibernate has a Session interface that provides many APIs to perform operations with the database. Here are below the Session interface methods we will use to develop CRUD operations with an example.

  • save(Object object) Method - save() method persists in the given transient instance, first assigning a generated identifier. (Or using the current value of the identifier property if the assigned generator is used.) This operation cascades to associated instances if the association is mapped with cascade="save-update".
  • saveOrUpdate(Object object) Method - This method either save(Object) or update(Object) the given instance, depending upon the resolution of the unsaved-value checks (see the manual for a discussion of unsaved-value checking). 
  • Session.delete(Object object) Method - Remove a persistent instance from the datastore.
  • Session.get() - This method returns a persistence object of the given class with the given identifier. It will return null if there is no persistence object.

Hibernate Save an Entity

Let's demonstrate how to save an entity into a database using Hibernate Session.save() method. The below diagram shows the snippet of saving an entity in a database:
The below snippet shows how to save an entity to a database:
package net.javaguides.hibernate;

import java.util.List;

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

import net.javaguides.hibernate.entity.Student;
import net.javaguides.hibernate.util.HibernateUtil;

public class App {
    public static void main(String[] args) {

        Student student = new Student("Ramesh", "Fadatare", "[email protected]");
        Student student1 = new Student("John", "Cena", "[email protected]");
        Transaction transaction = null;
        try (Session session = HibernateUtil.getSessionFactory().openSession()) {
            // start a transaction
            transaction = session.beginTransaction();
            // save the student objects
            session.save(student);
            session.save(student1);
            // commit transaction
            transaction.commit();
        } catch (Exception e) {
            if (transaction != null) {
                transaction.rollback();
            }
            e.printStackTrace();
        }

        try (Session session = HibernateUtil.getSessionFactory().openSession()) {
            List < Student > students = session.createQuery("from Student", Student.class).list();
            students.forEach(s - > System.out.println(s.getFirstName()));
        } catch (Exception e) {
            if (transaction != null) {
                transaction.rollback();
            }
            e.printStackTrace();
        }
    }
}
Read a complete step by step example at Hibernate Save an Entity Example.
We can also use Session.persist() method to save an entity into a database. 

Check out the below article:

Hibernate Read an Entity

In Hibernate, an entity can be obtained from a database using the following Session methods –

Session.get() → This method returns a persistence object of the given class with the given identifier. It will return null if there is no persistence object.

Session.load() → This method returns a persistence object of the given class with the given identifier. It will throw an exception ObjectNotFoundException if an entity does not exist in the database. The load() method may return a proxy object instead of a real persistence object.

Session.byId() → This method is used to obtain a persistence object by it being a primary identifier.
Before snippets read an entity from a database using Session.get()Session.load() and Session.byId() methods:
package net.javaguides.hibernate.dao;

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

import net.javaguides.hibernate.entity.Student;
import net.javaguides.hibernate.util.HibernateUtil;

public class StudentDao {
    public void getStudent(int id) {
        Transaction transaction = null;
        try (Session session = HibernateUtil.getSessionFactory().openSession()) {
            // start a transaction
            transaction = session.beginTransaction();

            // get Student entity using get() method
            Student student = session.get(Student.class, id);
            System.out.println(student.getFirstName());
            System.out.println(student.getEmail());

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

    public void loadStudent(int id) {
        Transaction transaction = null;
        try (Session session = HibernateUtil.getSessionFactory().openSession()) {
            // start a transaction
            transaction = session.beginTransaction();

            // get Student entity using load() method
            Student student = session.load(Student.class, id);
            System.out.println(student.getFirstName());
            System.out.println(student.getEmail());

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

    public void getStudentById(int id) {
        Transaction transaction = null;
        try (Session session = HibernateUtil.getSessionFactory().openSession()) {
            // start a transaction
            transaction = session.beginTransaction();

            // Obtain an entity using byId() method
            Student student = session.byId(Student.class).getReference(id);
            System.out.println(student.getFirstName());
            System.out.println(student.getEmail());

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

    public void saveStudent(Student student) {
        Transaction transaction = null;
        try (Session session = HibernateUtil.getSessionFactory().openSession()) {
            // start a transaction
            transaction = session.beginTransaction();
            // save the student object
            session.save(student);
            // commit transaction
            transaction.commit();
        } catch (Exception e) {
            if (transaction != null) {
                transaction.rollback();
            }
            e.printStackTrace();
        }
    }
}

Read a complete step by step example at Hibernate get(), load() and byId() Method Examples.

Hibernate Update an Entity

Let's write a code to demonstrate how to save or update an entity in the database using the saveOrUpdate() method. 

The below diagram shows the snippet of a saveOrUpdate() method:
The below snippet shows how to update an entity in a database. Here is the main App class which is used to connect MySQL database and persist Student object in a database table. Let's test Hibernate application to connect to the MySQL database.
package net.javaguides.hibernate;

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

import net.javaguides.hibernate.entity.Student;
import net.javaguides.hibernate.util.HibernateUtil;

public class App {
    public static void main(String[] args) {
        Student student = new Student("Ramesh", "Fadatare", "[email protected]");
        saveOrUpdateStudent(student);
    }

    public static void saveOrUpdateStudent(Student student) {
        Transaction transaction = null;
        try (Session session = HibernateUtil.getSessionFactory().openSession()) {
            // start a transaction
            transaction = session.beginTransaction();
            // save the student object
            session.saveOrUpdate(student);

            // get entity from database
            Student student2 = session.get(Student.class, 1);

            // do changes 
            student2.setFirstName("Ram");

            // update the student object
            session.saveOrUpdate(student2);

            // commit transaction
            transaction.commit();
        } catch (Exception e) {
            if (transaction != null) {
                transaction.rollback();
            }
            e.printStackTrace();
        }
    }
}
Read a complete step by step example at Hibernate 5 - saveOrUpdate() Method Example.

Hibernate Delete or Remove an Entity

In Hibernate, an entity can be removed from a database by calling the Session.delete() or Session.remove(). Using these methods, we can remove a transient or persistent object from the datastore.

The following snippets or examples demonstrate the use of Session.delete() and Session.remove() methods.

Session.delete(Object object) Method

EntityManager.remove(Object entity)

Remove the entity instance.
The following example snippet deletes transient and persistent objects from the datastore using Session.delete() method.
package net.javaguides.hibernate.dao;

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

import net.javaguides.hibernate.entity.Student;
import net.javaguides.hibernate.util.HibernateUtil;

public class SessionDeleteExample {
    public void deleteStudent(int id) {
        Transaction transaction = null;
        try (Session session = HibernateUtil.getSessionFactory().openSession()) {
            // start a transaction
            transaction = session.beginTransaction();

            // Delete a persistent object
            Student student = session.get(Student.class, id);
            if (student != null) {
                session.delete(student);
                System.out.println("student 1 is deleted");
            }

            // Delete a transient object
            Student student2 = new Student();
            student2.setId(2);
            session.delete(student2);
            System.out.println("Student 2 is deleted");

            // commit transaction
            transaction.commit();
        } catch (Exception e) {
            if (transaction != null) {
                transaction.rollback();
            }
            e.printStackTrace();
        }
    }
}
The following example snippet deletes transient and persistent objects from the datastore using Session.remove() method.
package net.javaguides.hibernate.dao;

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

import net.javaguides.hibernate.entity.Student;
import net.javaguides.hibernate.util.HibernateUtil;

public class SessionRemoveExample {
    public void removeStudent(int id) {
        Transaction transaction = null;
        try (Session session = HibernateUtil.getSessionFactory().openSession()) {
            // start a transaction
            transaction = session.beginTransaction();

            // Delete a persistent object
            Student student = session.get(Student.class, id);
            if (student != null) {
                session.remove(student);
                System.out.println("student 1 is deleted");
            }

            // Delete a transient object
            Student student2 = new Student();
            student2.setId(2);
            session.remove(student2);
            System.out.println("Student 2 is deleted");

            // commit transaction
            transaction.commit();
        } catch (Exception e) {
            if (transaction != null) {
                transaction.rollback();
            }
            e.printStackTrace();
        }
    }
}
Read a complete step by step example at Hibernate 5 - Delete or Remove an Entity Example.

Comments