Performing CRUD Operations Using Hibernate
Course: Advance Java Training
Topic: Performing CRUD Operations Using Hibernate
Course Link: Advance Java Training – JustAcademy
Demo Link: Register for a Course Demo
Website: JustAcademy Official Website
1. Introduction to CRUD Operations in Hibernate
CRUD stands for Create, Read, Update, and Delete. These are the four fundamental operations used to manage data in an application. Hibernate is a Java Object-Relational Mapping (ORM) framework that simplifies these operations by allowing developers to work with Java objects instead of manually writing SQL statements for every database interaction.
Hibernate maps Java entity classes to database tables and entity attributes to table columns. It translates persistence operations into appropriate database commands and manages entity states through a persistence context.
Learning Objectives
- Understand the meaning and importance of CRUD operations.
- Configure Hibernate for database connectivity.
- Create and map Java entity classes.
- Insert records using Hibernate.
- Retrieve records by identifier and query conditions.
- Update existing database records.
- Delete records safely using Hibernate.
- Understand transactions, sessions, and persistence contexts.
- Handle common exceptions and database errors.
- Build a complete CRUD application using Java and Hibernate.
2. What Is CRUD?
CRUD represents the basic operations required to manage persistent information in a database.
| Operation |
Purpose |
Typical SQL Command |
Hibernate API |
| Create |
Add a new record. |
INSERT |
session.persist() |
| Read |
Retrieve existing records. |
SELECT |
session.find() or query APIs |
| Update |
Modify existing records. |
UPDATE |
Modify a managed entity or use merge() when appropriate |
| Delete |
Remove an existing record. |
DELETE |
session.remove() |
Example Scenario
Consider an Employee Management System containing employee ID, name, email, and salary. CRUD operations allow the application to register a new employee, view employee information, change salary details, and remove an employee record.
3. Understanding Hibernate Components Used in CRUD
SessionFactory
SessionFactory is a shared, long-lived Hibernate component that creates Session instances. It contains mapping and configuration information and is generally initialized once for each database configuration.
Session
A Session provides the main interface for interacting with Hibernate. It manages a persistence context, tracks managed entity changes, and coordinates database operations.
Transaction
A transaction groups database operations into a logical unit of work. It allows changes to be committed when successful or rolled back when a failure occurs.
Entity
An entity is a Java class mapped to persistent database data. For example, an Employee class can represent rows in an employees table.
Persistence Context
The persistence context tracks managed entity instances and their changes. Hibernate uses it to maintain entity identity and detect modifications to managed objects.
4. Setting Up the Hibernate Project
Before implementing CRUD operations, create a Java project and configure the Hibernate dependencies, database driver, connection settings, and entity mappings.
Required Components
- Java Development Kit (JDK).
- Maven or Gradle for dependency management.
- Hibernate ORM.
- MySQL or another supported relational database.
- The appropriate JDBC driver.
- A Java entity class.
- A Hibernate configuration and SessionFactory setup.
Example Maven Dependencies
Add compatible versions of Hibernate ORM and the MySQL JDBC driver to the project's pom.xml. The following illustrates the dependency structure; use versions appropriate for your Java and Jakarta Persistence environment.
<dependencies>
<dependency>
<groupId>org.hibernate.orm</groupId>
<artifactId>hibernate-core</artifactId>
<version>YOUR_COMPATIBLE_VERSION</version>
</dependency>
<dependency>
<groupId>com.mysql</groupId>
<artifactId>mysql-connector-j</artifactId>
<version>YOUR_COMPATIBLE_VERSION</version>
</dependency>
</dependencies>
Replace the version placeholders with compatible released versions. Avoid mixing incompatible Hibernate and Jakarta Persistence dependencies.
5. Creating the Database and Table
For this tutorial, we will use a database named companydb and an employees table.
CREATE DATABASE companydb;
USE companydb;
CREATE TABLE employees (
id BIGINT PRIMARY KEY,
name VARCHAR(100) NOT NULL,
email VARCHAR(150) NOT NULL UNIQUE,
salary DECIMAL(12, 2) NOT NULL
);
The table contains four columns. The id column uniquely identifies each employee, while email has a uniqueness constraint to prevent duplicate email addresses.
6. Creating the Employee Entity
The Employee entity maps the Java object to the employees database table. Hibernate uses its annotations to determine how each attribute should be persisted.
package com.example.entity;
import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.Id;
import jakarta.persistence.Table;
import java.math.BigDecimal;
@Entity
@Table(name = "employees")
public class Employee {
@Id
private Long id;
@Column(nullable = false, length = 100)
private String name;
@Column(nullable = false, unique = true, length = 150)
private String email;
@Column(nullable = false, precision = 12, scale = 2)
private BigDecimal salary;
public Employee() {
}
public Employee(Long id, String name, String email,
BigDecimal salary) {
this.id = id;
this.name = name;
this.email = email;
this.salary = salary;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public BigDecimal getSalary() {
return salary;
}
public void setSalary(BigDecimal salary) {
this.salary = salary;
}
}
Explanation of Annotations
@Entity marks the class as a persistent entity.
@Table(name = "employees") maps the class to the employees table.
@Id defines the primary key.
@Column specifies column-related mapping information.
BigDecimal is appropriate for salary values that require decimal precision.
- The no-argument constructor supports entity instantiation by the persistence provider.
In this example, identifiers are assigned by the application. If your database uses generated identifiers, configure an appropriate @GeneratedValue strategy instead.
7. Configuring Hibernate
Create a Hibernate configuration file named hibernate.cfg.xml in the application's resources directory.
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"https://hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="hibernate.connection.driver_class">
com.mysql.cj.jdbc.Driver
</property>
<property name="hibernate.connection.url">
jdbc:mysql://localhost:3306/companydb
</property>
<property name="hibernate.connection.username">
app_user
</property>
<property name="hibernate.connection.password">
${DB_PASSWORD}
</property>
<property name="hibernate.show_sql">true</property>
<property name="hibernate.format_sql">true</property>
<mapping class="com.example.entity.Employee"/>
</session-factory>
</hibernate-configuration>
Security note: The password placeholder is illustrative and is not automatically substituted in every Hibernate configuration setup. Supply credentials through an appropriate environment-specific configuration mechanism or secure secrets manager. Do not commit real database passwords to source control.
Creating the SessionFactory
package com.example.util;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
public class HibernateUtil {
private static final SessionFactory SESSION_FACTORY =
new Configuration()
.configure("hibernate.cfg.xml")
.buildSessionFactory();
public static SessionFactory getSessionFactory() {
return SESSION_FACTORY;
}
public static void shutdown() {
SESSION_FACTORY.close();
}
}
The SessionFactory is initialized once and reused. Close it during application shutdown. Framework-based applications should generally use their framework's recommended lifecycle and transaction management.
8. CREATE Operation: Inserting Records
The Create operation inserts a new record into the database. In Hibernate, the session.persist() method makes a new entity persistent and schedules its insertion.
Steps for Creating a Record
- Create an Employee object.
- Open a Hibernate Session.
- Begin a transaction.
- Call
session.persist() with the entity.
- Commit the transaction.
- Close the Session and release resources.
Example: Insert an Employee
package com.example;
import com.example.entity.Employee;
import com.example.util.HibernateUtil;
import org.hibernate.SessionFactory;
import java.math.BigDecimal;
public class CreateEmployee {
public static void main(String[] args) {
SessionFactory sessionFactory =
HibernateUtil.getSessionFactory();
try {
sessionFactory.inTransaction(session -> {
Employee employee = new Employee(
101L,
"Aarav Sharma",
"[email protected]",
new BigDecimal("45000.00")
);
session.persist(employee);
});
System.out.println("Employee created successfully.");
} finally {
HibernateUtil.shutdown();
}
}
}
Explanation
- The Employee object contains the information to be stored.
sessionFactory.inTransaction() manages the Session and transaction for the callback.
session.persist(employee) registers the entity for insertion.
- The transaction helper commits when the callback succeeds and handles rollback on failure.
- The SessionFactory is closed after the application finishes using it.
Equivalent SQL Concept
INSERT INTO employees (id, name, email, salary)
VALUES (
101,
'Aarav Sharma',
'[email protected]',
45000.00
);
Hibernate generates the SQL according to the entity mapping and database configuration. The actual statement and execution timing may differ depending on identifier generation, flushing, and Hibernate version.
Important Points About CREATE
- Use
persist() for a new entity.
- Ensure the primary key is valid when identifiers are application-assigned.
- Validate required fields before persistence.
- Handle unique-constraint and foreign-key violations.
- Commit the transaction to complete the unit of work.
9. READ Operation: Retrieving Records
The Read operation retrieves existing records. Hibernate supports primary-key lookups, HQL queries, Criteria queries, and native SQL queries.
Reading a Record by Primary Key
The session.find() method retrieves an entity using its class and identifier. It returns null when no matching entity is found.
package com.example;
import com.example.entity.Employee;
import com.example.util.HibernateUtil;
public class ReadEmployee {
public static void main(String[] args) {
try {
HibernateUtil.getSessionFactory()
.inTransaction(session -> {
Employee employee =
session.find(Employee.class, 101L);
if (employee != null) {
System.out.println(
"ID: " + employee.getId()
);
System.out.println(
"Name: " + employee.getName()
);
System.out.println(
"Email: " + employee.getEmail()
);
System.out.println(
"Salary: " + employee.getSalary()
);
} else {
System.out.println(
"Employee not found."
);
}
});
} finally {
HibernateUtil.shutdown();
}
}
}
Reading Multiple Records with HQL
Hibernate Query Language (HQL) works with entity names and Java attributes instead of directly targeting table and column names.
import com.example.entity.Employee;
import java.util.List;
List<Employee> employees = session
.createQuery(
"from Employee e order by e.name",
Employee.class
)
.getResultList();
for (Employee employee : employees) {
System.out.println(
employee.getId() + " - " + employee.getName()
);
}
Filtering Records with Parameters
List<Employee> employees = session
.createQuery(
"from Employee e where e.salary > :minimumSalary",
Employee.class
)
.setParameter(
"minimumSalary",
new BigDecimal("40000.00")
)
.getResultList();
The named parameter :minimumSalary makes the query easier to read and avoids unsafe string concatenation of user-provided values.
Reading a Single Record by Email
Employee employee = session
.createQuery(
"from Employee e where e.email = :email",
Employee.class
)
.setParameter("email", "[email protected]")
.uniqueResult();
This example assumes the email is unique. If no record exists, the result is null; if multiple rows match, a non-unique result exception can occur.
Important Points About READ
- Use
find() for primary-key lookups.
- Use HQL or Criteria queries for filtering and sorting.
- Use parameterized queries for user-provided values.
- Use pagination for large result sets.
- Remember that lazy associations may not be initialized when the Session closes.
10. UPDATE Operation: Modifying Records
The Update operation modifies existing database information. A common Hibernate approach is to load the entity into the current persistence context, change its attributes, and commit the transaction.
Steps for Updating a Record
- Open a Session and begin a transaction.
- Retrieve the existing entity using its primary key.
- Check that the entity exists.
- Modify its attributes.
- Commit the transaction.
- Hibernate detects changes to the managed entity and synchronizes them with the database.
Example: Updating an Employee's Salary
package com.example;
import com.example.entity.Employee;
import com.example.util.HibernateUtil;
import java.math.BigDecimal;
public class UpdateEmployee {
public static void main(String[] args) {
try {
HibernateUtil.getSessionFactory()
.inTransaction(session -> {
Employee employee =
session.find(Employee.class, 101L);
if (employee != null) {
employee.setSalary(
new BigDecimal("52000.00")
);
System.out.println(
"Employee salary updated."
);
} else {
System.out.println(
"Employee not found."
);
}
});
} finally {
HibernateUtil.shutdown();
}
}
}
How Hibernate Updates the Record
The Employee instance is managed by the current Session. When its salary changes, Hibernate can detect the modification through dirty checking and generate an UPDATE statement when the persistence context is flushed.
UPDATE employees
SET salary = 52000.00
WHERE id = 101;
The SQL above illustrates the general operation. Actual SQL may include additional columns or parameter placeholders depending on Hibernate settings and mapping metadata.
Updating a Detached Entity with merge()
Sometimes an entity is modified after the original Session has closed. Such an entity is detached. The merge() method copies its state into a managed instance and returns that managed instance.
Employee detachedEmployee = obtainEmployeeFromAnotherLayer();
try (var session =
HibernateUtil.getSessionFactory().openSession()) {
var transaction = session.beginTransaction();
Employee managedEmployee =
(Employee) session.merge(detachedEmployee);
transaction.commit();
}
The method obtainEmployeeFromAnotherLayer() is illustrative and must be implemented by the application. Use the returned managed entity when subsequent managed changes are required. Merging detached state without validation can overwrite fields with stale or unintended values, so apply appropriate authorization and update rules.
Important Points About UPDATE
- Load and modify managed entities when practical.
- Use transactions for modifications.
- Check whether the record exists before updating.
- Validate incoming data and business rules.
- Use
merge() correctly when working with detached entities.
- Be careful with bulk updates because they can bypass normal entity-level dirty checking.
11. DELETE Operation: Removing Records
The Delete operation removes a record from the database. Hibernate's session.remove() method marks a managed entity for deletion.
Steps for Deleting a Record
- Open a Session.
- Begin a transaction.
- Retrieve the entity to delete.
- Check whether the entity exists.
- Call
session.remove().
- Commit the transaction.
Example: Delete an Employee
package com.example;
import com.example.entity.Employee;
import com.example.util.HibernateUtil;
public class DeleteEmployee {
public static void main(String[] args) {
try {
HibernateUtil.getSessionFactory()
.inTransaction(session -> {
Employee employee =
session.find(Employee.class, 101L);
if (employee != null) {
session.remove(employee);
System.out.println(
"Employee deleted successfully."
);
} else {
System.out.println(
"Employee not found."
);
}
});
} finally {
HibernateUtil.shutdown();
}
}
}
Equivalent SQL Concept
DELETE FROM employees
WHERE id = 101;
The SQL represents the general operation. Hibernate schedules the deletion and executes it when the persistence context is flushed, usually as part of completing the transaction.
Important Points About DELETE
- Confirm the correct entity before deleting it.
- Use transactions for deletion operations.
- Consider foreign-key constraints and dependent records.
- Understand cascade-remove behavior before configuring it.
- Apply authorization checks before deleting sensitive records.
12. Understanding Transactions in CRUD Operations
A transaction groups database changes into one logical operation. It helps prevent partially completed work and supports reliable persistence.
Transaction Methods
| Method |
Purpose |
beginTransaction() |
Starts a Hibernate transaction. |
commit() |
Commits the transaction when operations succeed. |
rollback() |
Abandons uncommitted changes after a failure. |
isActive() |
Checks whether the transaction remains active. |
Example with Explicit Rollback Handling
import org.hibernate.Session;
import org.hibernate.Transaction;
Transaction transaction = null;
try (Session session =
HibernateUtil.getSessionFactory().openSession()) {
transaction = session.beginTransaction();
Employee employee = new Employee(
102L,
"Meera Patel",
"[email protected]",
new BigDecimal("48000.00")
);
session.persist(employee);
transaction.commit();
} catch (RuntimeException e) {
if (transaction != null && transaction.isActive()) {
transaction.rollback();
}
throw e;
}
When using explicit transaction handling, roll back an active transaction if an operation fails. The exception should be logged or translated at the appropriate application boundary rather than silently ignored.
13. Session Management and Persistence Context
A Hibernate Session manages the persistence context, which contains the entity instances currently associated with it. The persistence context allows Hibernate to track changes and maintain one managed representation of a particular entity identity within that context.
Common Entity States
| State |
Description |
| Transient |
The object has been created but is not associated with a persistence context. |
| Persistent or Managed |
The object is associated with an active persistence context. |
| Detached |
The object was previously managed but is no longer associated with that context. |
| Removed |
The managed object has been scheduled for deletion. |
Why Session Management Matters
- Sessions should be short-lived and associated with a clear unit of work.
- A Session is not generally thread-safe and should not be shared across concurrent threads.
- Sessions should be closed when application-managed work is complete.
- Managed entities are automatically tracked for changes.
- Lazy associations may require an active persistence context to be fetched.
14. Difference Between persist(), merge(), and remove()
| Method |
Purpose |
Typical Usage |
persist() |
Makes a new entity managed and schedules insertion. |
Creating a new record. |
merge() |
Copies an entity's state into a managed instance and returns that instance. |
Applying detached entity state. |
remove() |
Schedules a managed entity for deletion. |
Deleting an existing record. |
find() |
Retrieves an entity by identifier. |
Reading or loading an entity before modification. |
These methods interact with the persistence context. They do not necessarily execute SQL immediately; SQL execution may occur during flushing or transaction completion.
15. Using HQL for Update and Delete Operations
Hibernate Query Language can execute bulk update and delete statements. These operations are useful when many records must be modified without loading each entity individually.
Bulk Update Example
int updatedCount = session
.createMutationQuery(
"update Employee e " +
"set e.salary = :salary " +
"where e.department = :department"
)
.setParameter(
"salary",
new BigDecimal("60000.00")
)
.setParameter("department", "IT")
.executeUpdate();
Bulk Delete Example
int deletedCount = session
.createMutationQuery(
"delete from Employee e where e.salary < :minimum"
)
.setParameter(
"minimum",
new BigDecimal("20000.00")
)
.executeUpdate();
These examples use Hibernate's mutation-query API, available in modern Hibernate versions. Execute bulk modifications inside a transaction.
Important Considerations for Bulk Operations
- Bulk update and delete operations act directly on matching database rows.
- They can bypass normal entity-level lifecycle callbacks and dirty checking.
- Entities already loaded in the persistence context may become stale.
- Flush pending changes and clear or refresh affected managed state when appropriate.
- Review cascading, auditing, and business rules before using bulk deletion.
16. CRUD Operations Using a Service Class
Separating persistence logic from application entry points makes code easier to maintain and test. A service class can provide methods for creating, reading, updating, and deleting employees.
package com.example.service;
import com.example.entity.Employee;
import org.hibernate.SessionFactory;
import java.math.BigDecimal;
import java.util.List;
public class EmployeeService {
private final SessionFactory sessionFactory;
public EmployeeService(SessionFactory sessionFactory) {
this.sessionFactory = sessionFactory;
}
public void createEmployee(Employee employee) {
sessionFactory.inTransaction(session ->
session.persist(employee)
);
}
public Employee getEmployee(Long id) {
return sessionFactory.fromTransaction(session ->
session.find(Employee.class, id)
);
}
public List<Employee> getAllEmployees() {
return sessionFactory.fromTransaction(session ->
session.createQuery(
"from Employee e order by e.id",
Employee.class
).getResultList()
);
}
public boolean updateSalary(Long id, BigDecimal salary) {
return sessionFactory.fromTransaction(session -> {
Employee employee =
session.find(Employee.class, id);
if (employee == null) {
return false;
}
employee.setSalary(salary);
return true;
});
}
public boolean deleteEmployee(Long id) {
return sessionFactory.fromTransaction(session -> {
Employee employee =
session.find(Employee.class, id);
if (employee == null) {
return false;
}
session.remove(employee);
return true;
});
}
}
This service demonstrates transaction-scoped CRUD methods using Hibernate's transaction helpers. Production implementations should also validate inputs, enforce authorization, handle duplicate values, and translate persistence exceptions into appropriate application-level errors.
17. Complete CRUD Workflow
A typical Employee Management System performs the following workflow:
- Receive employee details from a form, API request, or another application component.
- Validate the input and apply business rules.
- Create an Employee entity and persist it within a transaction.
- Retrieve employee information by identifier or through a query.
- Modify the managed entity and commit the transaction.
- Remove the entity when deletion is authorized and appropriate.
- Handle transaction failures and return meaningful results to the caller.
Workflow Diagram
Start
|
v
Receive User Request
|
v
Validate Input
|
v
Open Session / Begin Transaction
|
v
Choose CRUD Operation
|
+---- Create ----> persist()
|
+---- Read ------> find() / Query
|
+---- Update ----> Modify Managed Entity
|
+---- Delete ----> remove()
|
v
Commit Transaction
|
v
Return Result
|
v
Close Session / Finish
18. Common CRUD Errors and Troubleshooting
| Error |
Possible Cause |
Solution |
| Connection failure |
Database is unavailable or connection settings are incorrect. |
Check database status, JDBC URL, driver, and credentials. |
| Duplicate primary key |
An identifier already exists. |
Use a valid identifier or configure a suitable generation strategy. |
| Unique constraint violation |
An email or other unique value already exists. |
Validate uniqueness and handle the database exception. |
| Entity is not mapped |
The entity is missing from Hibernate's mapping metadata. |
Check annotations and entity registration. |
| Transaction not committed |
The transaction did not complete successfully. |
Check commit logic, exceptions, and transaction boundaries. |
| Record not found |
The requested identifier does not exist. |
Handle a null result from find(). |
| Foreign key constraint error |
A related record is missing or referenced data cannot be deleted. |
Check entity relationships and referential integrity. |
| LazyInitializationException |
An unfetched association is accessed outside the required persistence context. |
Fetch required data within an appropriate transaction. |
| Stale update |
Concurrent changes or outdated entity state caused a conflict. |
Consider optimistic locking with @Version and handle conflicts. |
19. Security and Performance Best Practices
- Use parameterized HQL and Criteria queries instead of concatenating user input into query strings.
- Validate input before persisting or modifying data.
- Use least-privilege database credentials.
- Never expose passwords or confidential connection information in public code.
- Keep transaction and Session lifetimes appropriately short.
- Use pagination when reading large collections.
- Inspect generated SQL when diagnosing slow database operations.
- Use appropriate indexes for frequently queried columns.
- Apply authorization checks before updates and deletions.
- Use optimistic locking where concurrent modification is a concern.
- Prefer reviewed database migrations for production schema changes.
- Log errors without exposing sensitive information.
20. Practical Exercises
Exercise 1: Create Operation
- Create a Product entity with id, name, price, and category.
- Configure the database connection and entity mapping.
- Insert at least five products using Hibernate.
- Verify the inserted records in the database.
Exercise 2: Read Operation
- Retrieve a product by primary key.
- Display all products using HQL.
- Filter products by category.
- Retrieve products above a specified price using a named parameter.
Exercise 3: Update Operation
- Find a product using its identifier.
- Modify its price and category.
- Commit the transaction.
- Verify the updated values in the database.
Exercise 4: Delete Operation
- Retrieve a product before deleting it.
- Remove the product inside a transaction.
- Handle cases where the product does not exist.
- Verify that the database record has been removed.
21. Mini Project: Employee Management System
Build an Employee Management System using Java, Hibernate, and MySQL. The application should allow users to manage employee information through CRUD operations.
Project Requirements
- Create an employees table with id, name, email, and salary columns.
- Create and configure the Employee entity.
- Implement a service class for CRUD operations.
- Insert new employees and retrieve existing employees.
- Update employee salaries and contact information.
- Delete employees after validating the request.
- Use transactions and appropriate exception handling.
- Test duplicate email addresses and invalid identifiers.
- Verify SQL statements and database results.
Expected Outcome
After completing the project, you should understand how Java objects are persisted, retrieved, updated, and deleted through Hibernate, as well as how sessions, transactions, and mapping configurations support these operations.
22. Interview Questions and Answers
Q1. What does CRUD stand for?
Answer: CRUD stands for Create, Read, Update, and Delete. These operations form the foundation of data management in most applications.
Q2. Which Hibernate method is used to insert a new entity?
Answer: The session.persist() method makes a new entity persistent and schedules its insertion into the database.
Q3. How can you retrieve an entity by its primary key?
Answer: Use session.find(EntityClass.class, id). It returns the entity or null if the entity is not found.
Q4. How does Hibernate update a managed entity?
Answer: Modify the entity while it is managed by the persistence context. Hibernate detects the changes through dirty checking and synchronizes them during flushing.
Q5. Which method removes an entity?
Answer: The session.remove() method schedules a managed entity for deletion.
Q6. What is the purpose of a Hibernate transaction?
Answer: A transaction groups database operations into a unit of work and allows changes to be committed or rolled back.
Q7. What is the difference between persist() and merge()?
Answer: persist() makes a new entity managed. merge() copies the state of an entity into a managed instance and returns that instance.
Q8. Does persist() immediately execute an INSERT statement?
Answer: Not necessarily. It schedules the entity for insertion. SQL execution may occur during a flush, which often happens before transaction commit.
Q9. What is dirty checking?
Answer: Dirty checking is Hibernate's ability to detect changes made to managed entities and synchronize them with the database.
Q10. Why should CRUD operations use transactions?
Answer: Transactions help preserve data consistency and provide a way to commit successful changes or roll back failed operations.
Q11. How can you update multiple records with Hibernate?
Answer: A parameterized HQL mutation query can update multiple matching rows. Such operations require careful transaction handling because they bypass normal entity-level dirty checking.
Q12. What happens when a record does not exist during a read operation?
Answer: A primary-key lookup with find() returns null. The application should handle this case appropriately.
Q13. What is the N+1 query problem?
Answer: It occurs when an initial query loads entities and additional queries are executed for related data, often once per entity. Appropriate fetch joins, batch fetching, or query redesign can reduce the problem.
Q14. How should database credentials be protected?
Answer: Store credentials in secure configuration or a secrets manager, avoid committing them to source control, and use a database account with limited privileges.
23. Quick Revision Checklist
- Understand CRUD and its four operations.
- Know how Hibernate maps Java entities to database tables.
- Understand SessionFactory, Session, and Transaction.
- Practice inserting records with
persist().
- Retrieve records using
find() and HQL.
- Update managed entities using dirty checking.
- Understand
merge() for detached entity state.
- Delete entities with
remove().
- Use transactions and handle rollback correctly.
- Understand persistence-context behavior and entity lifecycle states.
- Use parameterized queries and validate user input.
- Practice CRUD operations with a complete database-backed project.
24. Conclusion
Performing CRUD operations using Hibernate is an essential skill for Java developers who build database-driven applications. Hibernate reduces repetitive database-access code and provides object-oriented APIs for creating, reading, updating, and deleting persistent entities.
By learning persist(), find(), managed entity updates, merge(), and remove(), developers can understand how Hibernate coordinates entity state with database operations. Proper transaction management, secure query practices, input validation, and session lifecycle management are crucial for building reliable applications.
Learn More with JustAcademy
Explore the Advance Java Training course to develop your knowledge of Java, Hibernate ORM, database connectivity, and enterprise application development.
To learn more about the course, register for a course demo.
Visit the JustAcademy official website for additional course details and learning resources.