Full Stack • Java • System Design • Cloud • AI Engineering

Hibernate Entity Lifecycle Explained

Learn Hibernate Entity Lifecycle in depth including Transient, Persistent, Detached, and Removed states with real-world examples, diagrams, code examples, persistence context, dirty checking, merge vs update, and interview questions.

What You Will Learn

  • What is Entity Lifecycle?
  • Why Entity Lifecycle Matters
  • Entity States
  • Transient State
  • Persistent State
  • Detached State
  • Removed State
  • Persistence Context
  • Dirty Checking
  • Merge vs Update
  • Spring Data JPA Internals
  • Enterprise Examples
  • Interview Questions

Introduction

One of the most important Hibernate concepts is:

Entity Lifecycle

Most developers learn:

repository.save(user);

But don't understand:

What happens internally?

How Hibernate tracks entities?

When SQL executes?

Why updates happen automatically?

The answer is:

Entity Lifecycle

What is an Entity?

An Entity is a Java object mapped to a database table.

Example:

@Entity
@Table(name="USERS")
public class User {

    @Id
    private Long id;

    private String name;

    private String email;
}

Database Table:

USERS
-------------------

ID

NAME

EMAIL

What is Entity Lifecycle?

Entity Lifecycle describes how Hibernate manages an object during its lifetime.

Every Entity moves through:

Transient

↓

Persistent

↓

Detached

↓

Removed

Entity Lifecycle Diagram

flowchart LR

A[Transient]

B[Persistent]

C[Detached]

D[Removed]

A --> B

B --> C

B --> D

Why Is This Important?

Understanding lifecycle helps explain:

Dirty Checking

Caching

Transactions

Lazy Loading

Merge

Update

Performance Issues

Real World Analogy

Think about:

Employee Joining Company

States:

Candidate

↓

Employee

↓

Ex Employee

↓

Deleted Record

Hibernate entities behave similarly.


Lifecycle Overview

State Managed By Hibernate
Transient No
Persistent Yes
Detached No
Removed Yes

State 1: Transient

Transient means:

Object Exists

Only In Memory

Hibernate does not know about it.


Example

User user = new User();

user.setId(1L);

user.setName("Venu");

Current State:

Transient

Architecture

flowchart LR

A[Java Object]

B[Memory]

A --> B

No database interaction.


Characteristics

Not Stored In DB

Not Managed

No Persistence Context

No Dirty Checking

Example

User user = new User();

System.out.println(
    user.getName()
);

Output:

Venu

No SQL executed.


Moving To Persistent State

Call:

session.persist(user);

or

session.save(user);

State 2: Persistent

Persistent means:

Hibernate Is Tracking Entity

Example

Session session =
sessionFactory.openSession();

session.persist(user);

State:

Persistent

Architecture

flowchart LR

A[Entity]

B[Persistence Context]

C[Database]

A --> B
B --> C

What Happens Internally?

Hibernate:

Stores Entity

In Persistence Context

Tracks Changes

Example

User user =
session.get(
User.class,
1L
);

Generated SQL:

SELECT *

FROM USERS

WHERE ID=1;

Persistence Context

Persistence Context is:

Hibernate Memory Area

For Managed Entities

Persistence Context Architecture

flowchart LR

A[Session]

B[Persistence Context]

C[Entity]

A --> B

B --> C

Entity Becomes Managed

User user =
session.get(
User.class,
1L
);

Now Hibernate tracks:

Every Field Change

Dirty Checking

One of Hibernate's most powerful features.


Example

User user =
session.get(
User.class,
1L
);

user.setName("David");

No update query written.


What Happens?

Hibernate detects:

Name Changed

Venu → David

Automatically.


Dirty Checking Flow

flowchart LR

A[Load Entity]

B[Modify Entity]

C[Hibernate Detects Change]

D[Generate Update SQL]

A --> B
B --> C
C --> D

Generated SQL

UPDATE USERS

SET NAME='David'

WHERE ID=1;

Automatically.


Why No Save Call?

Because entity is:

Persistent

Hibernate already manages it.


State 3: Detached

Detached means:

Entity Exists

But No Longer Managed

Example

User user =
session.get(
User.class,
1L
);

session.close();

State:

Detached

Detached Architecture

flowchart LR

A[Entity]

B[Outside Session]

A --> B

Characteristics

Not Tracked

No Dirty Checking

No Automatic Updates

Example

user.setName("Mike");

No SQL generated.

Why?

Detached Entity

Common Detached Scenario

REST API:

Request 1

↓

Entity Loaded

↓

Session Closed

↓

Entity Returned

Entity becomes detached.


State 4: Removed

Entity scheduled for deletion.


Example

User user =
session.get(
User.class,
1L
);

session.remove(user);

State:

Removed

Removed Flow

flowchart LR

A[Persistent]

B[Removed]

C[Delete SQL]

A --> B
B --> C

Generated SQL

DELETE

FROM USERS

WHERE ID=1;

Complete Lifecycle Flow

flowchart LR

A[New Object]

B[Persist]

C[Managed]

D[Detach]

E[Removed]

A --> B
B --> C
C --> D
C --> E

Entity Lifecycle Example

Step 1

User user = new User();

State:

Transient

Step 2

session.persist(user);

State:

Persistent

Step 3

session.close();

State:

Detached

Step 4

session.remove(user);

State:

Removed

Merge vs Update

Frequently asked interview topic.


Merge

Reattaches detached entity.

User mergedUser =
session.merge(user);

Merge Flow

flowchart LR

A[Detached]

B[Merge]

C[Persistent]

A --> B
B --> C

Example

User detachedUser =
loadUser();

Session session =
sessionFactory.openSession();

session.merge(detachedUser);

Hibernate starts tracking again.


Update

session.update(user);

Reattaches entity directly.


Difference

Merge Update
Returns Managed Copy Uses Same Object
Safer Less Flexible
Preferred Legacy Style

Spring Data JPA Internals

When you call:

repository.save(user);

Hibernate performs:

Persist

Or

Merge

based on entity state.


save() Flow

flowchart LR

A[Entity]

B[Save Operation]

C[Persist]

D[Merge]

A --> B

B --> C
B --> D

Enterprise Banking Example

Account Service:

Account account =
repository.findById(1L)
          .get();

account.setBalance(
account.getBalance() - 100
);

What Happens?

Entity Loaded

Persistent State

Balance Changed

Dirty Checking

Automatic Update

Generated SQL

UPDATE ACCOUNT

SET BALANCE=900

WHERE ID=1;

Common Production Problems

Problem 1

Detached Entity Exception

LazyInitializationException

Problem 2

Unexpected Updates

Caused by:

Dirty Checking

Problem 3

Memory Leaks

Large Persistence Context.


Best Practices

✅ Keep Transactions Short

✅ Understand Entity States

✅ Use Merge For Detached Objects

✅ Monitor Persistence Context Size

✅ Avoid Long Running Sessions


Interview Questions

What are Hibernate Entity States?

Transient

Persistent

Detached

Removed

What is Persistent State?

Entity managed by Hibernate.


What is Detached Entity?

Entity no longer associated with Session.


What is Dirty Checking?

Automatic detection of modified entity fields.


Does Dirty Checking Work For Detached Entities?

No

What Happens When Session Closes?

Entities become:

Detached

Difference Between Merge And Update?

Merge creates managed copy.

Update reuses existing object.


Which State Supports Automatic SQL Updates?

Persistent

Key Takeaways

  • Every Hibernate Entity moves through lifecycle states.
  • Transient entities exist only in memory.
  • Persistent entities are managed by Hibernate.
  • Detached entities are no longer tracked.
  • Removed entities are scheduled for deletion.
  • Dirty Checking works only for Persistent entities.
  • Understanding Entity Lifecycle is essential for mastering Hibernate and Spring Data JPA.