Basic CRUD operations with Hibernate 6 involve creating, reading, updating, and deleting records in a database using Hibernate ORM. Hibernate simplifies these operations through its API.
Below is an explanation of each CRUD operation along with corresponding examples:
1. Create (Insert)
To save a new object in the database, you use the persist()
or save()
method provided by Hibernate.
SessionFactory factory = new Configuration()
.configure("hibernate.cfg.xml")
.addAnnotatedClass(Student.class)
.buildSessionFactory();
try (Session session = factory.openSession()) {
// Create a new student entity
Student student = new Student("Jane Doe");
// Start a transaction
session.beginTransaction();
// Save the entity to the database
session.persist(student);
// Commit the transaction
session.getTransaction().commit();
System.out.println("Student saved successfully with ID: " + student.getId());
} finally {
factory.close();
}
2. Read (Retrieve)
Hibernate’s get()
or find()
method is used to retrieve data from the database. You can fetch an object by its primary key.
try (Session session = factory.openSession()) {
// Start a transaction (optional if only querying)
session.beginTransaction();
// Retrieve a student by their primary key (ID)
int studentId = 1; // Example ID
Student retrievedStudent = session.get(Student.class, studentId);
System.out.println("Retrieved Student: " + retrievedStudent);
// Commit the transaction
session.getTransaction().commit();
}
3. Update
To modify an existing object in the database, you first retrieve it, make changes to its fields, and then let Hibernate update it within a transaction.
try (Session session = factory.openSession()) {
// Start a transaction
session.beginTransaction();
// Retrieve the student entity we want to update
int studentId = 1; // Example ID
Student studentToUpdate = session.get(Student.class, studentId);
// Modify the entity (e.g., update the name)
if (studentToUpdate != null) {
studentToUpdate.setName("Updated Name");
}
// Hibernate automatically tracks changes and applies them during commit
session.getTransaction().commit();
System.out.println("Student updated successfully.");
}
4. Delete
To delete an object, retrieve it first and use the delete()
method to remove it from the database.
try (Session session = factory.openSession()) {
// Start a transaction
session.beginTransaction();
// Retrieve the student to delete by their primary key
int studentId = 1;
Student studentToDelete = session.get(Student.class, studentId);
// Delete the entity if it exists
if (studentToDelete != null) {
session.delete(studentToDelete);
System.out.println("Student deleted successfully.");
}
// Commit the transaction
session.getTransaction().commit();
}
Keynotes for Hibernate 6:
- Ensure you have the correct Hibernate dependencies in
pom.xml
(for Maven) orbuild.gradle
(for Gradle). - You must configure
hibernate.cfg.xml
, including database connection properties and mapping annotated classes. - Always manage your Hibernate
Session
andSessionFactory
carefully, and close them when done to free resources. - Hibernate 6 has slight differences in config (e.g., Jakarta imports). Ensure you’re using the correct versions of annotations and configs (
jakarta.persistence
instead ofjavax.persistence
).
For the provided code, it already demonstrates correct usage of creating a SessionFactory
, opening a Session
, performing a transaction for persist()
, and closing resources. The same principles apply for all CRUD operations—use beginTransaction()
, perform the operation, and commit()
the transaction.
Maven Dependencies
<dependencies>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>6.4.4.Final</version>
</dependency>
</dependencies>