Object States
Object States Interview with follow-up questions
1. Can you explain the different states of a Hibernate object?
Hibernate entities move through four lifecycle states during their existence:
1. Transient
The object exists in memory but has no association with a Hibernate Session and no row in the database. Created with new; Hibernate is completely unaware of it. No identifier is assigned by the ORM.
2. Persistent (Managed)
The object is associated with an open Session (persistence context) and has a corresponding database row. Hibernate tracks all field changes via dirty checking and flushes them as SQL at transaction commit or explicit flush. This state is entered via persist(), find(), merge(), or any query result.
3. Detached
The Session has been closed (or the object was explicitly detached with evict() / detach()). The entity still holds a valid database ID, but changes are no longer tracked. To persist changes, the object must be re-associated with a new Session using merge(), which returns a new managed instance.
4. Removed
remove() has been called on a persistent entity. Hibernate schedules a DELETE for the next flush. The object should not be used after this call.
Transition diagram:
Transient ──persist()──► Persistent ──remove()──► Removed
│ │
session.close() evict()/detach()
│ │
└──────────► Detached
│
merge() ──► Persistent (new managed copy)
> Common interview point: merge() does not make the passed-in detached object persistent — it returns a new persistent instance with the detached object's state copied into it.
Follow-up 1
What is a Transient state?
An object is in the transient state if it is not associated with any Hibernate session. It is not yet persistent and has no representation in the database.
Follow-up 2
What is a Persistent state?
An object is in the persistent state if it is associated with a Hibernate session and has a representation in the database. Any changes made to the object will be tracked and synchronized with the database.
Follow-up 3
What is a Detached state?
An object is in the detached state if it was previously associated with a Hibernate session but is no longer. It still has a representation in the database, but any changes made to the object will not be automatically synchronized with the database.
Follow-up 4
How does an object transition between these states?
An object transitions between these states through the following steps:
Transient to Persistent: An object can transition from the transient state to the persistent state by associating it with a Hibernate session using the
save()orpersist()method.Persistent to Detached: An object can transition from the persistent state to the detached state by closing the Hibernate session or by evicting the object from the session using the
evict()method.Detached to Persistent: An object can transition from the detached state to the persistent state by reassociating it with a Hibernate session using the
update()ormerge()method.Detached to Transient: An object can transition from the detached state to the transient state by deleting it from the database using the
delete()method.
2. What happens when a Hibernate object is in the Transient state?
When a Hibernate object is in the Transient state, it has been created with the new keyword but has not yet been associated with a Hibernate Session (persistence context). Key characteristics:
- No database row: there is no corresponding record in the database.
- No assigned ORM identifier: Hibernate has not generated or assigned a primary key (unless the developer set one manually).
- Not tracked: Hibernate is completely unaware of the object. No dirty checking, no change synchronization.
- Garbage collectible: if no Java reference points to it, the object is eligible for GC with no database impact.
Transitioning out of Transient:
Call session.persist(entity) (or em.persist(entity)) to make the object Persistent. At the next flush (or immediately for some ID generation strategies like IDENTITY), Hibernate inserts the row:
Product product = new Product(); // Transient
product.setName("Widget");
product.setPrice(new BigDecimal("9.99"));
em.persist(product); // Now Persistent
// At transaction commit: INSERT INTO product (...) VALUES (...)
> Gotcha: calling merge() on a transient object (one with no ID) will insert it, similar to persist(), but returns a new managed instance rather than managing the original object in-place.
Follow-up 1
How can an object enter the Transient state?
An object can enter the Transient state in the following ways:
- Instantiating a new object using the
newkeyword. - Detaching an object from a Hibernate Session using the
evict()orclear()methods. - Loading an object from the database using a different persistence framework or directly using JDBC.
Follow-up 2
Can a Transient object be garbage collected?
Yes, a Transient object can be garbage collected. Since it is not associated with any Hibernate Session, Hibernate does not keep any references to the object. Once there are no other references to the object, it becomes eligible for garbage collection.
Follow-up 3
What happens when we try to persist a Transient object?
When we try to persist a Transient object, Hibernate will throw a TransientObjectException. This exception is thrown because Hibernate cannot determine the state of the object and whether it should be inserted or updated in the database. To persist a Transient object, it needs to be associated with a Hibernate Session by either loading it from the database or by using the save() or persist() methods.
3. Can you describe the Persistent state in Hibernate?
An entity in the Persistent (also called Managed) state is attached to an open Hibernate Session (or JPA EntityManager) and has a corresponding row in the database.
Key characteristics:
- Automatic dirty checking: Hibernate takes a snapshot of the entity's state when it enters the persistence context. At flush time it compares the current state to the snapshot and automatically issues
UPDATESQL for any changed fields — no manualupdate()call is needed.
@Transactional
public void updateEmail(Long userId, String newEmail) {
User user = em.find(User.class, userId); // loaded as Persistent
user.setEmail(newEmail); // just a setter
// Hibernate generates: UPDATE user SET email = ? WHERE id = ?
}
First-level cache: within the same Session, loading the same entity by ID twice returns the same Java object — no second database query.
Identity guarantee: within a Session, only one Java instance can represent a given database row. This prevents aliasing bugs.
Cascading: operations on the persistent entity can cascade to associated entities based on
cascadesettings on the relationship annotations.
Exiting Persistent state:
- Session closes → entity becomes Detached.
em.remove(entity)→ entity becomes Removed.em.detach(entity)→ entity becomes Detached immediately.
Follow-up 1
How can an object enter the Persistent state?
An object can enter the Persistent state in Hibernate through the following ways:
By using the
save()orpersist()method: These methods are used to save a new object into the database and associate it with a session. The object will then enter the Persistent state.By using the
get()orload()method: These methods are used to retrieve an object from the database and associate it with a session. The object will then enter the Persistent state.By using the
update()method: This method is used to reattach a detached object to a session. The object will then enter the Persistent state.
Follow-up 2
What happens when we modify a Persistent object?
When we modify a Persistent object in Hibernate, the changes made to the object will be automatically tracked by Hibernate. These changes will be synchronized with the database when the session is flushed or committed. Hibernate uses dirty checking to detect the changes made to the object and generate the necessary SQL statements to update the corresponding database records.
Follow-up 3
How does Hibernate track changes in a Persistent object?
Hibernate tracks changes in a Persistent object by using dirty checking. Dirty checking is the process of comparing the current state of an object with its original state to determine if any changes have been made. Hibernate keeps a copy of the original state of the object when it is first loaded or saved into the session. When the session is flushed or committed, Hibernate compares the current state of the object with its original state and generates the necessary SQL statements to update the database records for the modified properties.
4. What does it mean when a Hibernate object is in the Detached state?
An entity in the Detached state was previously Persistent (associated with an open Session) but is no longer attached to any active persistence context.
How an entity becomes Detached:
- The
Session/EntityManagerthat managed it was closed. em.detach(entity)orsession.evict(entity)was called explicitly.em.clear()was called, detaching all entities in the context.
Key characteristics:
- The entity still has a valid primary key and represents a database row.
- Changes are NOT tracked: modifying fields on a detached entity has no database effect — Hibernate does not know about it.
- The entity can be passed across layers (e.g., from service to controller, or serialized over a network) without holding a database connection open.
Re-attaching a Detached entity:
Use merge() to create a new Persistent copy with the detached object's current state:
// detachedProduct was loaded in a previous transaction
detachedProduct.setPrice(new BigDecimal("19.99")); // change not tracked yet
@Transactional
public Product save(Product detachedProduct) {
return em.merge(detachedProduct); // returns a new Persistent instance
// UPDATE is issued at commit
}
> Gotcha: accessing a lazy-loaded collection on a detached entity throws LazyInitializationException because there is no open Session to execute the SQL. Use @EntityGraph, JOIN FETCH, or @Transactional to ensure collections are loaded while still attached.
Follow-up 1
How can an object enter the Detached state?
An object can enter the Detached state in several ways:
- When a transaction ends or a session is closed, all the objects associated with that session become detached.
- Explicitly detaching an object using the
session.evict()orsession.clear()methods. - When a persistent object is serialized and then deserialized, it becomes detached.
Follow-up 2
What happens when we modify a Detached object?
When we modify a Detached object, Hibernate is not aware of the changes. The changes made to the object will not be automatically synchronized with the database. To persist the changes, we need to reattach the object to a Hibernate session and explicitly save or update it.
Follow-up 3
How can we reattach a Detached object?
To reattach a Detached object, we can use the session.update() or session.merge() methods. The update() method reattaches the object and marks it for update, while the merge() method merges the state of the detached object with the persistent object in the session. After reattaching the object, we can make further modifications and save or update it to persist the changes.
5. How does Hibernate manage the state transitions of an object?
Hibernate manages entity state transitions automatically through the persistence context (Session / EntityManager) and the current transaction. The developer triggers transitions by calling specific API methods; Hibernate handles all the database synchronization.
Transition mechanisms:
| From | To | Trigger |
|---|---|---|
| Transient | Persistent | persist(), save() (legacy), or a cascading persist from a parent |
| Persistent | Removed | remove() |
| Persistent | Detached | close(), evict(), detach(), clear() |
| Detached | Persistent | merge() returns a new managed copy |
| Removed | Persistent | persist() called again before flush |
Dirty checking (auto-synchronization):
When a Persistent entity's fields change, Hibernate detects this at flush time by comparing the current state to the snapshot taken at load time. Changed fields are written with an UPDATE statement — no explicit save call is needed.
Flush timing:
By default (FlushMode.AUTO), Hibernate flushes:
- Before executing a query (to ensure queries see the latest in-memory changes).
- At transaction commit.
Cascade types (CascadeType.PERSIST, CascadeType.MERGE, CascadeType.REMOVE, CascadeType.ALL) propagate state transitions from a parent entity to its associated child entities automatically.
> Interview gotcha: calling merge() on a detached entity does NOT make the original object persistent. It copies the state into a new (or existing) managed instance and returns that. The detached object remains detached.
Follow-up 1
What role does the Session play in managing object states?
The Session in Hibernate plays a crucial role in managing object states. It acts as a bridge between the application and the database. The Session is responsible for loading objects from the database, tracking changes made to the objects, and persisting the changes back to the database. It also manages the lifecycle of objects, including the creation, retrieval, updating, and deletion of objects. The Session provides methods to perform these operations, such as save, update, delete, and get.
Follow-up 2
How does Hibernate handle state transitions during transactions?
Hibernate handles state transitions during transactions by maintaining a first-level cache, also known as the session cache. When an object is loaded or saved, it is stored in the session cache. During a transaction, any changes made to the objects are tracked in the session cache. When the transaction is committed, Hibernate synchronizes the changes in the session cache with the database. If an object is loaded multiple times within the same session, Hibernate ensures that only one instance of the object is present in the session cache.
Follow-up 3
Can you give an example of a state transition in Hibernate?
Sure! Let's consider an example where we have a User entity class mapped to a database table. Initially, the User object is in the transient state. When we call the save method on the Hibernate Session to persist the object, it transitions to the persistent state. Any changes made to the object will be tracked by Hibernate. For example, if we update the User object's name property, Hibernate will detect the change. When the session is flushed or the transaction is committed, Hibernate will synchronize the updated name property with the database, transitioning the object to the persistent state with the updated value.
6. What is the difference between merge() and persist() in Hibernate/JPA?
Both methods are used to save data, but they operate on different entity states and have important behavioral differences.
persist(entity)
- Transitions a Transient entity to the Persistent (Managed) state.
- The entity must not already have a manually assigned ID that exists in the database (for
@GeneratedValueIDs this is not an issue). - The INSERT is typically deferred until flush time.
- Returns void; the passed instance itself becomes managed.
merge(entity)
- Works with Detached entities (entities that were previously managed but the session/entity manager was closed).
- Copies the state of the detached entity into a new managed instance (or an existing managed instance if one with the same ID is already in the persistence context).
- Returns a new managed instance — the original detached object is NOT managed after the call.
- If no row exists with that ID, an INSERT is performed; if one does exist, an UPDATE is performed.
Critical interview gotcha:
// WRONG — common mistake
Order detached = getDetachedOrder();
em.merge(detached);
detached.setStatus("CANCELLED"); // has NO effect — detached is still detached!
// CORRECT
Order managed = em.merge(detached);
managed.setStatus("CANCELLED"); // this will be flushed
Summary table:
persist() |
merge() |
|
|---|---|---|
| Input state | Transient | Detached (or Transient) |
| Returns | void | Managed copy |
| Use case | New entity | Reconnecting detached entity |
Live mock interview
Mock interview: Object States
- Read your scene and goals
- Talk it out; goals tick off live
- Get a score and stronger lines
Your voice and your AI key never touch our servers; the key stays in this browser and is sent only to Google. Only your round scores are saved to track progress.