CRUD acronyms to CREATE, READ, UPDATE AND DELETE. In this article, we will learn how to perform Create, read, update, and delete operations in Hibernate.
What is CRUD Operation?
CRUD Operations are Create, Read, Update and Delete. These are the most basic and vital operations that we perform in any web application.
- These are the most basic and important operations that we perform in an application.
- As we know, Hibernate is an ORM tool that will map the object to the database and has a session Interface that provides many APIs to perform this operation.
How to perform CRUD In Hibernate?
The Session Interface provides us some methods to perform CRUD in Hibernate. Let’s see in detail.
- save(Object object): This method will persist the state of an object and return a generated identifier.
- saveOrUpdate(Object object): This method will either save or update an entity value.
- delete(Object object): This method returns the persisted object.
- get(): This method returns the persistence object of the class specified.
Let’s see each method:
- Saving an Entity
// 1. Create a Session Session session = HibernateUtil.getSessionFactory().openSession(); // 2. Begin a Transaction Transaction tx = null; tx = session.beginTransaction(); // 3.save the object session.save(entityName); // 4. Commit the transaction. tx.commit(); session.close();
- Reading an Entity
// 1. create a List List<EntityName> list = new ArrayList<Doctor>(); // 2. Get the session Session session = HibernateUtil.getSessionFactory().openSession(); // 3. Create Query Query query = session.createQuery("from EntityName"); list = query.list(); return list;
- Updating an Entity
// 1. Create a Session Session session = HibernateUtil.getSessionFactory().openSession(); // 2. begin a Transaction Transaction tx = null; tx = session.beginTransaction(); // 3. Update a Entity session.update(Entity Object); tx.commit(); session.close();
- Deleting or removing an Entity
Session session = HibernateUtil.getSessionFactory().openSession(); Transaction tx = null; tx = session.beginTransaction(); EntityName entityObject= (EntityName ) session.load(Doctor.class, id); session.delete(entityObject); tx.commit(); session.close();
Example of CRUD in Hibernate
Below are the steps to create a simple CRUD using Hibernate.
- Create a dynamic project in eclipse and add the jar files into the project. How to add the jar file you can check it here Environment Set up for Hibernate.
- Also, you can create a maven project and add the dependencies into the pom.xml file.
Project Structure
pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com</groupId> <artifactId>Hibernate_CRUD_Example</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>jar</packaging> <name>Hibernate_CRUD_Example</name> <url>http://maven.apache.org</url> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> </properties> <dependencies> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>3.8.1</version> <scope>test</scope> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>8.0.21</version> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>3.1.0</version> </dependency> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-core</artifactId> <version>4.0.1.Final</version> </dependency> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-validator</artifactId> <version>4.2.0.Final</version> </dependency> <dependency> <groupId>org.hibernate.common</groupId> <artifactId>hibernate-commons-annotations</artifactId> <version>4.0.1.Final</version> <classifier>tests</classifier> </dependency> <dependency> <groupId>org.hibernate.javax.persistence</groupId> <artifactId>hibernate-jpa-2.0-api</artifactId> <version>1.0.1.Final</version> </dependency> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-entitymanager</artifactId> <version>4.0.1.Final</version> </dependency> <!-- https://mvnrepository.com/artifact/net.sf.ehcache/ehcache --> <dependency> <groupId>net.sf.ehcache</groupId> <artifactId>ehcache</artifactId> <version>2.10.9.2</version> </dependency> <!-- https://mvnrepository.com/artifact/org.hibernate/hibernate-ehcache --> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-ehcache</artifactId> <version>4.0.1.Final</version> </dependency> </dependencies> </project>
- Now, Create hibernate.cfg.xml for more detail on this file you can check here How to configure hibernate in Java application.
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd"> <hibernate-configuration> <session-factory> <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property> <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/college</property> <property name="hibernate.connection.username">root</property> <property name="hibernate.connection.password">root</property> <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property> <property name="hibernate.jdbc.batch_size">50</property> <property name="hibernate.show_sql">true</property> <property name="format_sql">true</property> <property name="hibernate.hbm2ddl.auto">update</property> <mapping class="com.Hibernate_CRUD_Example.Doctor" /> </session-factory> </hibernate-configuration>
- Now, we will create a Helper class, HibernateUtil.java to keep session Object.
package com.Hibernate_CRUD_Example; import org.hibernate.SessionFactory; 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 return new Configuration().configure().buildSessionFactory(); } catch (Throwable ex) { // Make sure you log the exception to track it System.err.println("SessionFactory failed." + ex); throw new ExceptionInInitializerError(ex); } } public static SessionFactory getSessionFactory() { return sessionFactory; } public static void shutdown() { // Optional but can be used to Close caches and connection pools getSessionFactory().close(); } }
- Now, we will create an entity class of Doctor.java for setting and getting data. We are creating annotated-based classes so we won’t need a mapping file now. (for annotation you can see the previous article How to use Annotation in Hibernate?)
package com.Hibernate_CRUD_Example; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Table; @Entity @Table(name = "DOCTOR") public class Doctor { @Id @Column(name = "ID") @GeneratedValue (strategy = GenerationType.AUTO) private int id; @Column(name = "D_NAME") private String doctorName; @Column(name = "D_SPECIALITY") private String doctorSpeciality; @Column(name = "D_EMAIL") private String doctorEmail; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getDoctorName() { return doctorName; } public void setDoctorName(String doctorName) { this.doctorName = doctorName; } public String getDoctorSpeciality() { return doctorSpeciality; } public void setDoctorSpeciality(String doctorSpeciality) { this.doctorSpeciality = doctorSpeciality; } public String getDoctorEmail() { return doctorEmail; } public void setDoctorEmail(String doctorEmail) { this.doctorEmail = doctorEmail; } }
- Now, we will add one more layer called the Data Access Object layer to interact with the database. Create a DoctorDao.java in src/main/java/com/Hibernate_CRUD_Example.
package com.Hibernate_CRUD_Example; import java.util.ArrayList; import java.util.List; import org.hibernate.Query; import org.hibernate.Session; import org.hibernate.Transaction; public class DoctorDao { // Add a Doctor public void addDoctor(Doctor doctor) { // 1. Create a Session Session session = HibernateUtil.getSessionFactory().openSession(); // 2. Begin a Transaction Transaction tx = null; tx = session.beginTransaction(); // 3.save the object session.save(doctor); // 4. Commit the transaction. tx.commit(); session.close(); } // Read the data @SuppressWarnings("unchecked") public List<Doctor> getAllDoctors() { // 1. create a List List<Doctor> list = new ArrayList<Doctor>(); // 2. Get the session Session session = HibernateUtil.getSessionFactory().openSession(); Query query = session.createQuery("from Doctor"); list = query.list(); return list; } // Get user by id: public Doctor getDoctorById(int id) { Doctor doctor = null; Session session = HibernateUtil.getSessionFactory().openSession(); doctor = (Doctor) session.get(Doctor.class, id); System.out.println("Doctor Name :" + doctor.getDoctorName()); return doctor; } // Update public void updateDoctor(Doctor doctor) { // 1. Create a Session Session session = HibernateUtil.getSessionFactory().openSession(); // 2. begin a Transaction Transaction tx = null; tx = session.beginTransaction(); // 3. Update a doctor session.update(doctor); tx.commit(); session.close(); } // Delete public void deleteDoctor(int id) { Session session = HibernateUtil.getSessionFactory().openSession(); Transaction tx = null; tx = session.beginTransaction(); Doctor doctor = (Doctor) session.load(Doctor.class, id); session.delete(doctor); tx.commit(); session.close(); } }
- Now, create a Test.java class to perform all these operations.
package com.Hibernate_CRUD_Example; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.Transaction; /** * Hello world! * */ public class Test { public static void main( String[] args ) { //Add New Doctor System.out.println("*************CRUD USING HIBERNATE***************"); System.out.println("*************Adding Doctor**********************"); Doctor doctor = new Doctor(); doctor.setDoctorName("Dr. A"); doctor.setDoctorSpeciality("Cardiologist"); doctor.setDoctorEmail("a@a.com"); System.out.println("\n"); Doctor doctor2 = new Doctor(); doctor2.setDoctorName("Dr. B"); doctor2.setDoctorSpeciality("ENT"); doctor2.setDoctorEmail("b@b.com"); DoctorDao dao = new DoctorDao(); dao.addDoctor(doctor); dao.addDoctor(doctor2); System.out.println("***************Doctor Successfully inserted *********"); //Get All Doctors System.out.println("***************Getting Doctor List *********"); for(Doctor readDoctor : dao.getAllDoctors()){ System.out.println("Id :" +readDoctor.getId()); System.out.println("Name :" +readDoctor.getDoctorName()); System.out.println("Speciality :" +readDoctor.getDoctorSpeciality()); System.out.println("Email :" +readDoctor.getDoctorEmail()); } //Get Doctor by Id. System.out.println("***************Getting Doctor by Id *********"); Doctor doctorById =dao.getDoctorById(1); //Here we pass the ID System.out.println("Id :" +doctorById.getId()); System.out.println("Name :" +doctorById.getDoctorName()); System.out.println("Speciality :" +doctorById.getDoctorSpeciality()); System.out.println("Email :" +doctorById.getDoctorEmail()); //Update a Doctor System.out.println("***************Update a Doctor *********"); doctor.setDoctorEmail("DrK@k.com"); doctor.setId(1); //whose email we have to change dao.updateDoctor(doctor); System.out.println("Doctor Email Id Successfully Updated"); //Delete a Doctor System.out.println("***************Delete a Doctor *********"); dao.deleteDoctor(1); //delete doctor with id 1. System.out.println("Doctor of ID 1 Successfully deleted"); } }
- Now, Just View the console window how these operation is getting executed. Also, view the database to see whether every operation is performed.
Hibernate: insert into DOCTOR (D_EMAIL, D_NAME, D_SPECIALITY) values (?, ?, ?) Hibernate: insert into DOCTOR (D_EMAIL, D_NAME, D_SPECIALITY) values (?, ?, ?) ***************Doctor Successfully inserted ********* ***************Getting Doctor List ********* Hibernate: select doctor0_.ID as ID0_, doctor0_.D_EMAIL as D2_0_, doctor0_.D_NAME as D3_0_, doctor0_.D_SPECIALITY as D4_0_ from DOCTOR doctor0_ Id :1 Name :Dr. A Speciality :Cardiologist Email :a@a.com Id :2 Name :Dr. B Speciality :ENT Email :b@b.com ***************Getting Doctor by Id ********* Hibernate: select doctor0_.ID as ID0_0_, doctor0_.D_EMAIL as D2_0_0_, doctor0_.D_NAME as D3_0_0_, doctor0_.D_SPECIALITY as D4_0_0_ from DOCTOR doctor0_ where doctor0_.ID=? Doctor Name :Dr. A Id :1 Name :Dr. A Speciality :Cardiologist Email :a@a.com ***************Update a Doctor ********* Hibernate: update DOCTOR set D_EMAIL=?, D_NAME=?, D_SPECIALITY=? where ID=? Doctor Email Id Successfully Updated ***************Delete a Doctor ********* Hibernate: select doctor0_.ID as ID0_0_, doctor0_.D_EMAIL as D2_0_0_, doctor0_.D_NAME as D3_0_0_, doctor0_.D_SPECIALITY as D4_0_0_ from DOCTOR doctor0_ where doctor0_.ID=? Hibernate: delete from DOCTOR where ID=? Doctor of ID 1 Successfully deleted
Thus, this is How we perform CRUD using Hibernate.