Hibernate/JPA CRUD Operations Methods

Author Avatar
Learn Here Fun Pedia
5 min read •

1. Hibernate/JPA CRUD Operations

There are two common APIs you'll encounter for data persistence in Java:

  • JPA / Jakarta Persistence: Uses EntityManager
  • Hibernate Native API: Uses Session

In Spring Boot, you'll most commonly work with the standard JPA hierarchy:

Spring Data JPA
      ↓
EntityManager
      ↓
Hibernate
      ↓
Database

So even if your code says employeeRepository.save(employee);, Hibernate is generally doing the heavy lifting underneath.

2. Create — persist()

In raw JPA, you use entityManager.persist(employee);

new Employee
      ↓
persist()
      ↓
Persistence Context
      ↓
MANAGED

Important: persist() does not necessarily mean "execute INSERT immediately." It means: Make this new entity managed by the persistence context. Hibernate can execute the actual SQL later during the flush.

@Transactional
public void createEmployee() {
    Employee employee = new Employee();
    employee.setName("Amit");
    entityManager.persist(employee);
    // Entity is now managed
}

Potential SQL timing: persist() → Persistence Context → flush() → INSERT → commit().

3. Read — find()

To read data: Employee employee = entityManager.find(Employee.class, 101L);

find(Employee, 101)
       ↓
First-Level Cache?
       ↓
Found → return managed entity
       ↓
Not found → SQL SELECT
       ↓
Persistence Context
       ↓
return entity

Hibernate only executes SELECT * FROM employee WHERE id = 101; if the entity isn't already managed or cached in the Persistence Context.

4. Update (Dirty Checking)

There isn't normally a JPA operation like entityManager.update(employee);. This is a very important concept. If the entity is already managed, Hibernate tracks its changes automatically!

Employee employee = entityManager.find(Employee.class, 101L);
employee.setSalary(60000);

This flow is called dirty checking:

Employee (salary = 50000)
       ↓
setSalary(60000)
       ↓
Dirty Checking
       ↓
Flush
       ↓
UPDATE

So: Managed entity + modification + flush = Hibernate generates UPDATE.

5. merge()

What if the entity is detached (no longer tracked by the persistence context)?

Employee managedEmployee = entityManager.merge(employee);

Important: merge() does not simply reattach the same object. Conceptually, it takes the detached employee, copies its state into a new managed copy, places that copy into the Persistence Context, and returns it. This distinction is frequently asked in interviews.

6. Delete — remove()

To delete, the entity must generally be managed:

Employee employee = entityManager.find(Employee.class, 101L);
entityManager.remove(employee);

Hibernate marks it for deletion (REMOVED state) and will later execute the DELETE statement upon flush.

7. CRUD Summary Table

Operation JPA Method Purpose
Create persist() Make new entity managed
Read find() Retrieve entity
Update Modify managed entity Dirty checking
Update detached merge() Copy state into managed entity
Delete remove() Mark managed entity for deletion

8. & 9. save() vs persist() vs merge()

This is another major interview area. When you use Spring Data JPA and write employeeRepository.save(employee);, Spring determines whether the entity is considered new.

  • If new: It internally calls persist()
  • If detached/existing: It internally calls merge()

Does save() Immediately Execute INSERT? Usually, not necessarily. The exact timing depends on the transaction context, flush mode, ID generation strategy, and entity state. Don't say "save() always means INSERT."


Interactive Look: The Entity Lifecycle

To really master these CRUD operations, you need to visualize how persist(), remove(), and merge() move objects between the four fundamental entity states. Explore the lifecycle diagram below:

diagram Idea: An interactive state machine illustrating the 4 JPA Entity Lifecycle states and the methods that transition them. Visual type: State machine diagram Data specification: - Data structure: Nodes representing states, edges representing JPA methods. - Initial values: Nodes: - New (Transient) - Managed (Persistent) - Detached - Removed Transitions: - New -> Managed (persist) - Managed -> Detached (clear/detach/close) - Detached -> Managed (merge) - Managed -> Removed (remove) - Removed -> Managed (persist - cancelling removal) - Managed -> Database (flush/commit - dirty checking) - Mapping: Nodes to circles/boxes, transitions to directed arrows with labels. User controls: Clickable nodes to see description of what the state means regarding the Persistence Context and Database. Interactivity: Click a node to highlight its incoming/outgoing transitions and show a detail panel explaining the state. Animation: Smooth highlighting of active paths when a node is selected.

T3 Interview Summary

If the interviewer asks: "Does save() immediately execute an INSERT query?"

"save() does not guarantee that the INSERT is immediately sent to the database. The SQL execution generally happens when Hibernate flushes the persistence context. However, ID generation strategies (like GenerationType.IDENTITY) can cause SQL to execute earlier because Hibernate immediately needs to retrieve the database-generated identifier before it can put the entity in the Persistence Context."

Important Interview Questions (FAQs)

Q1: How do you update an entity in JPA?

You retrieve it using find() so it becomes Managed, then you simply use standard Java setter methods to modify it. Hibernate's "Dirty Checking" mechanism automatically detects the changes and generates an UPDATE statement when the Persistence Context is flushed.

Q2: What is the exact difference between `persist()` and `merge()`?

persist() takes a newly instantiated (Transient) entity and makes it Managed by the Persistence Context. merge() takes a Detached entity (which has an ID but isn't currently tracked), copies its state onto a freshly loaded/tracked Managed instance, and returns that Managed instance. The original passed-in object remains detached.

Q3: Why doesn't `persist()` fire an INSERT immediately?

Hibernate utilizes a write-behind pattern. persist() simply adds the entity to the Persistence Context. The actual SQL INSERT is delayed until the session is flushed (usually right before a transaction commits). This allows Hibernate to batch multiple statements together for better performance.

Comments (0)