Hibernate CRUD Operations Example


In this article, we will discuss how to use Hibernate ORM Framework to perform CRUD operations against the MySQL database. 

Learn complete JPA at JPA Tutorial - Java Persistence API

Learn Hibernate ORM Framework at Hibernate Tutorial

Hibernate is a Java-based ORM tool that provides a framework for mapping application domain objects to relational database tables and vice versa. It provides a reference implementation of the Java Persistence API, which makes it a great choice as an ORM tool with the benefits of loose coupling.
CRUD operations are Create(save), Read(select), Update(update), and Delete(delete). 

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. 
  • 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 5 - Save an Entity Example.
We can also use the 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 a primary identifier.
Here are the code snippets that 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 into a database. Here is the main App class which is used to connect the MySQL database and persist Student object in a database table. 

Let's test Hibernate application to connect 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 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 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 database 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 database 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.
Learn complete JPA at JPA Tutorial - Java Persistence API

Learn Hibernate ORM Framework at Hibernate Tutorial

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