CRUD Operations using Hibernate (original) (raw)
Last Updated : 26 Mar, 2025
Hibernate is a powerful Java ORM (Object-Relational Mapping) framework that simplifies database interactions by mapping Java objects to relational tables. It allows developers to perform **CRUD operations (Create, Read, Update, Delete) without writing complex SQL queries.
In this article, we will cover:
- Setting up Hibernate with MySQL
- Performing CRUD operations with Hibernate
- Using SessionFactory for database transactions
CRUD refers to database operations:
- C -> Create/Insert
- R -> Retrieve
- U -> Update
- D -> Delete
Given below are the examples that illustrate the use of Hibernate to perform CRUD operations. All the examples use MySQL for database management and 'student_info' as a sample database.
Project Setup
Step 1: Create SessionFactoryProvider class
This class creates and returns a SessionFactory object.
**SessionFactoryProvider.java:
Java `
import org.hibernate.SessionFactory; import org.hibernate.cfg.Configuration;
public class SessionFactoryProvider {
public static SessionFactory provideSessionFactory() {
Configuration config = new Configuration();
// Configures Hibernate with hibernate.cfg.xml
config.configure();
return config.buildSessionFactory();
}
}
`
Step 2: Create a POJO Class
Let's create a POJO Class, this class represents the object persistent in the database.
**Student.java:
Java `
import javax.persistence.*;
@Entity public class Student { @Id private int id; private String name; private int std;
public Student() {
}
public Student(int id, String name, int std) {
this.id = id;
this.name = name;
this.std = std;
}
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 int getStd() {
return std;
}
public void setStd(int std) {
this.std = std;
}
}
`
Step 3: Create Configuration file:
This configuration file provides database connection details, mapping resources, etc. In this file, the hibernate.hbm2ddl.auto property is set to create for creating tables in the database automatically. If the table already exists in the database, the property is set to update to alter the existing schema.
**hibernate.cfg.xml:
XML `
update com.mysql.cj.jdbc.Driver jdbc:mysql://localhost:3306/student_info?serverTimezone=UTC root root org.hibernate.dialect.MySQL8Dialect`
Inserting, Retrieving, Updating, and Deleting Records
**Creating a Table and Inserting a New Record:
The following method, session.saveOrUpdate(), is used to insert or update the object in the database.
**Create.java:
Java `
import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.Transaction; import utilities.SessionFactoryProvider;
public class Create { public static void main(String[] args) { SessionFactory sessionFactory = SessionFactoryProvider.provideSessionFactory(); Session session = sessionFactory.openSession(); Transaction t = session.beginTransaction();
Student s = new Student(101, "John", 10);
// Save or update the student record
session.saveOrUpdate(s);
t.commit();
session.close();
sessionFactory.close();
}
}
`
This code will insert the new record into the student_info table.
**Retrieving data from the database:
The following methods are used to retrieve the data from the database:
- **get(): Returns null if the object doesn't exist in the database.
T get(Class entityType, Serializable id)
- **load(): Throws ObjectNotFoundException if the object doesn't exist in the database.
T load(Class theClass, Serializable id)
get() vs load()
The below table demonstrates the difference between get() and load().
get() | load() |
---|---|
It returns null if the object doesn't exist in the database or session cache. | It throws ObjectNotFoundException if the object doesn't exist in the database or session cache. |
It returns fully initialized objects which may require multiple database classes. Therefore it affects the performance of the application. | It returns a proxy object and initializes the object only if any method is called on the object(other than getId()). Therefore it results in better performance. |
get() is used to fetch an object when it is not sure whether the object exists or not. | load() is used to fetch an object if it is sure that object exists. |
**Retrieve.java:
Java `
import org.hibernate.Session; import org.hibernate.SessionFactory; import utilities.SessionFactoryProvider;
public class Retrieve { public static void main(String[] args) { SessionFactory sessionFactory=SessionFactoryProvider.provideSessionFactory(); Session session=sessionFactory.openSession();
Student s=session.get(Student.class, 101);
System.out.println("Id : "+s.getId());
System.out.println("Name : "+s.getName());
System.out.println("Class : "+s.getStd());
sessionFactory.close();
}
}
`
The following details will be fetched from the database:
If an object doesn't exist in database, get() returns null whereas load() throws ObjectNotFoundexception.
**Retrieve.java:
Java `
package crudOperations;
import org.hibernate.Session; import org.hibernate.SessionFactory; import beans.Student; import utilities.SessionFactoryProvider;
public class Retrieve { public static void main(String[] args) { SessionFactory sessionFactory = SessionFactoryProvider.provideSessionFactory(); Session session = sessionFactory.openSession();
// Fetching object using get()
System.out.println("Fetching object using get:");
Student s1 = session.get(Student.class, 102);
if (s1 != null) {
System.out.println("Id: " + s1.getId());
System.out.println("Name: " + s1.getName());
System.out.println("Class: " + s1.getStd());
} else {
System.out.println("Student not found.");
}
sessionFactory.close();
}
}
`
**Output:
**Updating a record in the database:
**Update.java:
Java `
import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.Transaction; import utilities.SessionFactoryProvider;
public class Update { public static void main(String[] args) { SessionFactory sessionFactory = SessionFactoryProvider.provideSessionFactory(); Session session = sessionFactory.openSession(); Transaction t = session.beginTransaction();
Student s = session.get(Student.class, 101);
// Update the student's grade
s.setStd(11);
// Save the updated student record
session.saveOrUpdate(s);
t.commit();
session.close();
sessionFactory.close();
}
}
`
The following record will be updated:
**Deleting a record from the database:
To delete an object from the database, the session.delete() method is used.
**Delete.java:
Java `
import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.Transaction; import beans.Student; import utilities.SessionFactoryProvider;
public class Delete { public static void main(String[] args) { SessionFactory sessionFactory = SessionFactoryProvider.provideSessionFactory(); Session session = sessionFactory.openSession(); Transaction t = session.beginTransaction();
Student s = session.get(Student.class, 101);
// Delete the student record
session.delete(s);
t.commit();
session.close();
sessionFactory.close();
}
}
`
**Output: