Entity Mapping & Lifecycle : Hibernate

Author Avatar
Informative page
5 min read •

Entity Mapping & Lifecycle

Extremely Important: Understanding @Entity, Requirements, and the Persistence Flow

1. What is an Entity?

⭐⭐⭐⭐⭐

An entity is a Java object whose state is intended to be stored and managed in a relational database. When Hibernate sees @Entity, it understands: "This class is part of the persistence model. I need to manage objects of this class and map them to a database representation."

Java Database ------------------------------------------------ Employee class ───────→ employee table Employee object ───────→ employee row Employee fields ───────→ table columns
🔥 Interview Check: Does @Entity create a table?

Don't say "@Entity directly creates a table." That's an oversimplification. @Entity defines the class as a JPA entity. Whether a physical table is automatically created depends on schema-generation settings (like ddl-auto) or migration tools like Flyway/Liquibase.

2. The 6 Requirements of a JPA Entity

Simply writing class Employee {} is not enough. A proper JPA entity must follow these rules:

  • 1. Annotate with @Entity: Without it, JPA ignores the class entirely.
  • 2. Must have an Identifier (@Id): Every entity needs a unique identity so Hibernate knows exactly which database row this object represents.
  • 3. No-argument constructor: A public or protected protected Employee() {} is required so Hibernate can instantiate the entity when reading from the database.
  • 4. Class should not be final: Keep the class (and persistent methods/fields) non-final. Hibernate heavily relies on subclassing and proxies for features like lazy loading.
  • 5. Must be a Class, not an Interface: An entity represents persistent object state, so it needs an instantiable class model.
  • 6. Persistent state mapping: Fields represent the state that can be persisted. You can explicitly exclude fields using @Transient.

3. A Complete Basic Entity

Here is what a standard JPA entity looks like when all requirements are met:

@Entity @Table(name = "employee") public class Employee { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; private String name; private double salary; // Required by JPA protected Employee() {} public Employee(String name, double salary) { this.name = name; this.salary = salary; } }

4. The Entity Lifecycle (Crucial for Interviews)

⭐⭐⭐⭐⭐

An entity doesn't remain in one state throughout its lifetime. It moves through four major states:

persist() NEW ─────────────────────────→ MANAGED | | detach() / clear() ↓ DETACHED | | merge() ↓ MANAGED | | remove() ↓ REMOVED
  • NEW (Transient): new Employee(). The object exists in Java memory, but Hibernate is not managing it yet. There is no database identity.
  • MANAGED (Persistent): After calling persist() or fetching from DB. Hibernate is tracking this entity in the Persistence Context. This enables Dirty Checking and first-level caching.
  • DETACHED: The Java object still exists, but the persistence context has closed or the entity was explicitly detached. Hibernate is no longer tracking changes.
  • REMOVED: Marked for deletion. Upon flush/commit, Hibernate will issue an SQL DELETE.

5. Dirty Checking & Entity Identity

The Magic of Dirty Checking:
If an entity is in the MANAGED state, you do not need to explicitly call update() or save(). When you modify a field (e.g., employee.setSalary(60000);), Hibernate's dirty-checking mechanism detects the change automatically and issues the UPDATE SQL during the flush.

Entity Identity vs Java Object Identity:
In Java, new Employee() and another new Employee() are two different objects in memory. But in JPA, Entity Identity is based on the @Id. If you fetch ID 101 twice within the same persistence context, Hibernate will return the exact same Java object reference (First-Level Cache).

6. Rapid-Fire T3 Interview Questions

Q: Does creating an entity object automatically insert it into the database?

No. Employee e = new Employee(); only creates a Java object (NEW state). It must become managed (via persist()) and eventually be flushed within an active transaction for a database insert to occur.

Q: Why does an entity need a no-argument constructor?

Because the persistence provider uses reflection to instantiate entity objects dynamically, especially when materializing rows coming back from a database query.

Q: What happens when a managed entity is modified?

Hibernate's dirty-checking mechanism detects the field changes against its internal snapshot. During transaction flush, it automatically synchronizes those changes with the database by generating an SQL UPDATE.

The Mental Model (Memorize this flow)

Keep these concepts connected in your head. This is the foundation for almost everything in Hibernate:

@Entity → @Id (Identity) → Persistence Context → Managed Entity → Dirty Checking → Flush → SQL → Database

Comments (0)