In this article, we will discuss how to use Hibernate 5 to perform CRUD operations against the 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.
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 the relational database tables and vice versa. It provides a reference implementation of the Java Persistence API, that makes it a great choice as an ORM tool with benefits of loose coupling.
CRUD operations are Create(save), Read(select), Update(update) and Delete(delete). Hibernate has Session interface which provides many APIs to perform operations with database.
Here are below Session interface methods we will use to develop CRUD operations with an example.
- save(Object object) Method - save() method persist 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.
Video Tutorial
This tutorial is explained in below YouTube video. Subscribe to my youtube channel to learn more about Spring boot at Java Guides - YouTube Channel.
Hibernate 5 - Save an Entity
Let's demonstrate how to save an entity into a database using Hibernate Session.save() method. Below diagram shows the snippet of saving an entity in 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", "rameshfadatare@javaguides.com"); Student student1 = new Student("John", "Cena", "john@javaguides.com"); 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 Session.persist() method to save an entity into a database. Check out below article:
- Hibernate 5 - Persist an Entity Example - In this article, we will create a simple Hibernate application to demonstrate how to persist an entity into a database.
Hibernate 5 - 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.
Before snippets to 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();
}
}
}
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.
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 5 - get(), load() and byId() Method Examples.
Hibernate 5 - Update an Entity
Let's write a code to demonstrate how to save or update an entity in the database using the saveOrUpdate() method.
Below diagram shows the snippet of a saveOrUpdate() method:
Below snippet shows how to update an entity into a database. Here is 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 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", "rameshfadatare@javaguides.com"); 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 5 - 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 snappits or examples demonstrate the use of Session.delete() and Session.remove() methods.
The following snappits 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 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 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.
Learn complete JPA at JPA Tutorial - Java Persistence API
Learn Hibernate ORM Framework at Hibernate Tutorial
Related Hibernate Database Operations (Session Methods)
- Hibernate 5 - Save an Entity Example - In this article, we will create a simple Hibernate application to demonstrate how to save an entity into a database.
- Hibernate 5 - Persist an Entity Example - In this article, we will create a simple Hibernate application to demonstrate how to persist an entity into a database.
- Hibernate 5 - saveOrUpdate() Method Example - In this article, we will create a simple Hibernate application to demonstrate how to save or update an entity in the database using the saveOrUpdate() method.
- Hibernate 5 - get(), load() and byId() Method Examples - In this article, we will show you how to use Session.get(), Session.load() and Session.byId() methods to retrieve an entity from database.
- Hibernate 5 - merge() Example - In this article, we will show you how to use Session.merge() method to merge an entity in Hibernate Application.
- Hibernate 5 - Delete or Remove an Entity Example - 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.
- Hibernate 5 - load() Method Example - In this article, we will create a simple Hibernate application using Java configuration without using hibernate.cfg.xml to demonstrates the usage of Session.load() method.
- Hibernate 5 c3p0 Connection Pool Example - In this article, we will show how to use c3p0 connection pooling in hibernate applications.
Free Spring Boot Tutorial | Full In-depth Course | Learn Spring Boot in 10 Hours
Watch this course on YouTube at Spring Boot Tutorial | Fee 10 Hours Full Course
Comments
Post a Comment