CRUD Operations
CRUD (Create, Read, Update, Delete) operations are essential in any application that deals with data persistence. Hibernate provides convenient methods and APIs to perform these operations on the underlying database.
Let's quickly go through each of these operations in Hibernate:
- Create: To create a new record in the database, you can create an instance of the entity class, set its properties, and save it to the database using the
save()
method.
TEXT/X-JAVA
1// Create a new Employee object
2Employee employee = new Employee();
3employee.setFirstName("John");
4employee.setLastName("Doe");
5employee.setSalary(5000);
6
7// Save the employee to the database
8session.save(employee);
- Read: To retrieve a record from the database, you can use the
get()
method to fetch an entity object by its primary key.
TEXT/X-JAVA
1// Get an employee by id
2Employee employee = session.get(Employee.class, 1L);
3
4// Print employee details
5System.out.println("Employee ID: " + employee.getId());
6System.out.println("First Name: " + employee.getFirstName());
7System.out.println("Last Name: " + employee.getLastName());
8System.out.println("Salary: $" + employee.getSalary());
- Update: To update an existing record in the database, you can retrieve the entity object, modify its properties, and save it back using the
update()
method.
TEXT/X-JAVA
1// Get an employee by id
2Employee employee = session.get(Employee.class, 1L);
3
4// Update employee details
5employee.setSalary(6000);
6
7// Save the updated employee to the database
8session.update(employee);
- Delete: To remove a record from the database, you can retrieve the entity object and delete it using the
delete()
method.
TEXT/X-JAVA
1// Get an employee by id
2Employee employee = session.get(Employee.class, 1L);
3
4// Delete the employee from the database
5session.delete(employee);
These are the basic CRUD operations that you can perform using Hibernate. Hibernate takes care of generating the SQL statements and executing them on the database.
Now let's see these operations in action with the help of some executable Java code.
xxxxxxxxxx
84
}
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
public class Main {
public static void main(String[] args) {
// Create an instance of the SessionFactory
SessionFactory sessionFactory = new Configuration()
.configure()
.buildSessionFactory();
// Create a session
Session session = sessionFactory.openSession();
// Perform CRUD operations
createEmployee(session);
readEmployee(session);
updateEmployee(session);
deleteEmployee(session);
// Close the session
session.close();
// Close the SessionFactory
sessionFactory.close();
}
public static void createEmployee(Session session) {
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment