Hibernate Entity Lifecycle Explained

Oct 29, 2024

Hibernate Entity Lifecycle Explained

In Hibernate (and JPA), an entity lifecycle describes the different states an entity instance goes through during its interaction with the Persistence Context (Session / EntityManager) and the database.


🧩 Entity Lifecycle States

| State             | Description
|-------------------|----------------------------------------------------------------------------------
| **Transient**     | Newly created object, not yet associated with a Hibernate session. Not saved in DB.
| **Persistent**    | Associated with a Hibernate session and has a corresponding row in DB.
| **Detached**      | Was persistent, but session is closed or entity was evicted. Changes are not tracked.
| **Removed**       | Marked for deletion from DB, will be deleted upon commit.

🔄 Typical Lifecycle Flow

// Transient
User user = new User("Alice");

// Persistent
session.save(user);

// Detached
session.close(); // or session.evict(user);

// Removed
session.delete(user);

⚙️ Lifecycle Callbacks (JPA Annotations)

You can hook into these state transitions using annotations:

| Annotation     |              When it’s Called         |
|----------------|---------------------------------------|
| `@PrePersist`  | Before entity is persisted (inserted) |
| `@PostPersist` | After entity is persisted             |
| `@PreUpdate`   | Before entity is updated              |
| `@PostUpdate`  | After entity is updated               |
| `@PreRemove`   | Before entity is removed              |
| `@PostRemove`  | After entity is removed               |
| `@PostLoad`    | After entity is loaded from DB        |

Example:

@Entity
public class User {
    @Id
    private Long id;

    @PrePersist
    public void beforeSave() {
        System.out.println("About to persist: " + this);
    }

    @PostLoad
    public void afterLoad() {
        System.out.println("Entity loaded: " + this);
    }
}

🧠 Summary Diagram

   new (Transient)
        
        
  save()/persist()
        
        
   Persistent ──► remove() ──► Removed
        
  session.close()/evict()
        
     Detached
ilia-kritiuk.dev