On this page
- 1. · Concept & Definition
- 2. · Why It Matters
- 3. · How It Works
- Deep Dive — Flush and Dirty Checking
- 4. · Java / Jakarta EE Code Examples
- 5. · Configuration, Defaults & Diagnostics
- Deep Dive — Bulk Operations and the Lifecycle
- 6. · Production Usage Patterns
- 7. · Common Pitfalls & Misconceptions
- 8. · Best Practices
- 9. · Architect's Perspective & Trade-offs
- 10. · Interview Q&A
1· Concept & Definition
Every entity instance is, at any moment, in one of four lifecycle states: new (transient), managed (persistent), detached or removed. EntityManager operations and transaction boundaries move instances between these states, and the state determines whether changes are written, whether lazy associations can be loaded and what a subsequent operation will do.

2· Why It Matters
- The same setter call saves data or silently does nothing depending on the state.
- Detached entities crossing layer boundaries are a common source of bugs (merge semantics, lazy access).
- Lifecycle callbacks give a standard place for auditing and validation.
- Removal semantics interact with cascades and constraints.
Lifecycle mistakes are expensive because they rarely fail loudly. A change made to a detached entity is simply ignored, a managed entity modified in a read path is quietly written at commit, and a merge of a half-filled object replaces good data with nulls; none of these throws an exception, and all of them pass a happy-path test. The state model is also the vocabulary behind most persistence design choices: where transactions begin, what the web layer receives, how DTOs are mapped back and whether open-session-in-view is acceptable. Engineers who can say which state an object is in at each line of a service method write code with far fewer data-integrity defects.
3· How It Works
New
A new (transient) instance has just been created with new. It has no persistent identity in the database yet (its @Id may be null), the context knows nothing about it, and changes to it have no effect on any row. persist() makes it managed and schedules an INSERT; for IDENTITY generation, the INSERT must run immediately so the key can be obtained.
Managed
A managed instance belongs to a persistence context. Changes are detected by dirty checking and written at flush; lazy associations can be loaded; the instance is unique per primary key within that context. Instances become managed through persist, find, queries, merge (the returned copy) or by being reachable via a cascading association.
Detached
A detached instance has a persistent identity but is no longer associated with a context — after commit of a transaction-scoped context, after detach, clear, close, or after serialisation to another tier. Changes are not tracked, and traversing unloaded lazy associations throws LazyInitializationException. Reattachment is done with merge, which copies state into a managed instance.

Removed
A removed instance is managed but scheduled for deletion; the DELETE is issued at flush. Removing an entity that is referenced by other rows fails on the foreign key unless the references are cleared or removal cascades. Calling persist() on a removed entity before flush cancels the deletion.
| Operation on… | New | Managed | Detached | Removed |
|---|---|---|---|---|
persist | → managed | ignored (or cascade) | IllegalArgumentException (provider-dependent) | → managed again |
merge | → managed copy (INSERT) | returns same instance | → managed copy (state copied) | IllegalArgumentException |
remove | ignored | → removed | IllegalArgumentException | ignored |
refresh | IllegalArgumentException | reloads | IllegalArgumentException | provider-dependent |
detach | ignored | → detached | ignored | removal cancelled from context |
| Lifecycle callback | Fires |
|---|---|
@PrePersist / @PostPersist | Before/after INSERT |
@PreUpdate / @PostUpdate | Before/after UPDATE |
@PreRemove / @PostRemove | Before/after DELETE |
@PostLoad | After an entity is loaded or refreshed |
@EntityListeners(X.class) | Externalises callbacks (e.g. auditing) to a listener class |
Deep Dive — Flush and Dirty Checking
Managed state is useful only because of what happens at flush. When a transaction commits, or before a query whose results could be affected by pending changes, the provider compares each managed entity's current field values with the snapshot taken when it was loaded, and issues UPDATE statements only for the entities that changed. With the default flush mode AUTO, this is why a JPQL query sees changes made earlier in the same transaction. The cost grows with the number of managed entities, so a transaction that loads ten thousand rows merely to read them pays for comparing ten thousand snapshots at commit.
Two consequences follow. First, read-heavy paths and batch jobs should not accumulate managed entities: use DTO projections, read-only query hints, or periodic flush and clear in loops. Second, the order and timing of SQL belong to the provider, not to the code. Inserts, updates and deletes are grouped at flush, so a constraint violation can surface at commit, far from the line that caused it; calling em.flush() deliberately makes such errors appear where they can be handled.
@Transactional
public void importCustomers(List<CustomerRow> rows) {
int i = 0;
for (CustomerRow row : rows) {
em.persist(Customer.from(row)); // NEW -> MANAGED
if (++i % 500 == 0) {
em.flush(); // write this batch
em.clear(); // MANAGED -> DETACHED
}
}
}4· Java / Jakarta EE Code Examples
@Transactional
public long create(NewOrder in) {
// NEW: nothing in the database
Order o = new Order(in.number());
// MANAGED, INSERT scheduled
em.persist(o);
// tracked; no extra call needed
o.setStatus(OrderStatus.CONFIRMED);
// populated at/before flush
return o.getId();
// commit → INSERT (+UPDATE if needed)
}// Detached entity coming back from the web layer
@Transactional
public OrderDto update(OrderDto dto) {
Order detached = OrderMapper.toEntity(dto); // has an id, not managed
// state copied into managed instance
Order managed = em.merge(detached);
// use 'managed', not 'detached', from here on
return OrderMapper.toDto(managed);
}
// Safer alternative: load and apply explicit changes
@Transactional
public OrderDto applyChanges(long id, OrderPatch patch) {
Order o = em.find(Order.class, id);
if (o == null) throw new NotFoundException();
// only the intended fields change
patch.status().ifPresent(o::setStatus);
return OrderMapper.toDto(o);
}@Entity
@EntityListeners(AuditListener.class)
public class Order {
@PrePersist void onCreate() { createdAt = Instant.now(); }
@PreUpdate void onChange() { updatedAt = Instant.now(); }
}
public class AuditListener {
@PrePersist void audit(Object entity) { /* record who/what */ }
}org.hibernate.LazyInitializationException: failed to lazily initialize a collection of
role:
com.acme.Order.lines, could not initialize proxy - no Session
// outside the transaction
at com.acme.web.OrderMapper.toDto(OrderMapper.java:34)5· Configuration, Defaults & Diagnostics
| Symptom | State-related cause | Fix |
|---|---|---|
| Changes not saved | Entity is detached | Load inside the transaction or merge explicitly |
LazyInitializationException | Lazy access after the context closed | Fetch what is needed inside the transaction (join fetch, entity graph, DTO) |
| Unexpected UPDATE at commit | Managed entity modified accidentally | Avoid mutating entities in read paths; use read-only queries/DTOs |
| Data overwritten with stale values | merge of a partially populated detached entity | Apply explicit field changes to a loaded entity |
EntityExistsException | persist of an instance with an existing PK | Use merge or load first |
Deep Dive — Bulk Operations and the Lifecycle
Bulk JPQL and native statements operate directly on the database and do not pass through the persistence context: managed entities keep their old values, callbacks do not fire and @Version is not incremented unless the statement does it explicitly.
| Operation | Context updated? | Callbacks? | Version? | Guidance |
|---|---|---|---|---|
| Entity change + flush | Yes | Yes | Yes | Default for business logic |
Bulk JPQL UPDATE/DELETE | No | No | Only if set explicitly | Run first in a transaction, then em.clear() |
| Native SQL | No | No | No | Refresh or clear afterwards; consider second-level cache |
EntityManager.refresh | Yes (reloads) | @PostLoad | Reloaded | To resynchronise after bulk work |
@Transactional
public int expireOldCarts(Instant before) {
int updated = em.createQuery("""
UPDATE Cart c
SET c.status = :expired, c.version = c.version + 1
WHERE c.status = :open AND c.updatedAt < :before""")
.setParameter("expired", CartStatus.EXPIRED)
.setParameter("open", CartStatus.OPEN)
.setParameter("before", before)
.executeUpdate();
em.clear(); // managed copies are now stale
return updated;
}6· Production Usage Patterns
- Entities loaded, modified and flushed within one transactional service method.
- DTOs at layer boundaries; mapping back by loading the entity and applying changes.
- Auditing (created/updated by and at) implemented with entity listeners.
@Versionon aggregates so concurrent edits fail fast instead of silently overwriting.
7· Common Pitfalls & Misconceptions
- Using the argument passed to
mergeafterwards — it stays detached. - Open-session-in-view as a default — hides lazy loading problems and extends transactions.
- Removing a parent without handling children — foreign key violations.
- Heavy logic in lifecycle callbacks (remote calls, other queries) — runs at flush, inside the transaction.
8· Best Practices
- Decide consciously where entities are managed and keep them inside that boundary.
- Always use the instance returned by
merge. - Keep callbacks limited to setting fields and simple validation.
- Prefer explicit partial updates over merging whole detached graphs.
9· Architect's Perspective & Trade-offs
| Update strategy | Lost-update risk | Simplicity | Notes |
|---|---|---|---|
| Load + apply changes | Low (with @Version) | High | Recommended default |
merge of a full detached entity | High (stale fields overwrite) | High | Needs complete, fresh state |
| Bulk JPQL UPDATE | None (set-based) | Medium | Bypasses context; refresh/clear afterwards |
| Native SQL update | None | Medium | Context may hold stale copies |
10· Interview Q&A
Name the four entity lifecycle states.
New, managed, detached and removed. A new or transient instance has just been created with new and is unknown to any persistence context. A managed instance belongs to an open context, so its changes are tracked by dirty checking and written at flush. A detached instance has a database identity but is no longer associated with a context, typically because its transaction ended, so its changes are ignored and unloaded lazy associations cannot be fetched. A removed instance is still managed but scheduled for deletion at flush. The state, not the code you write, decides whether a setter call becomes an UPDATE, which is why the model matters in everyday work.
What makes an entity managed?
An instance is managed when it is associated with an open persistence context. That happens in five ways: calling persist on a new instance; loading it with find or getReference; receiving it as an entity result of a JPQL or criteria query; taking the instance returned by merge; and reaching it through an association cascaded with PERSIST or MERGE from an entity being persisted or merged. Within one context there is exactly one managed instance per primary key, so two finds for the same id return the same object. It stays managed until the context is closed or cleared, the entity is detached, or a transaction-scoped context ends with its transaction.
What is the difference between persist and merge?
persist takes a new instance, makes that same object managed and schedules an INSERT; it returns nothing, and calling it on an instance whose row already exists fails, with an exception that varies by provider and may appear only at flush. merge takes the state of any instance, finds or loads the managed instance with the same id, copies the state onto it and returns that managed copy, inserting a row if none exists. The argument passed to merge stays detached, so changes made to it afterwards are lost, a very common bug. Use persist for genuinely new entities, and merge only to reattach detached state you know is complete and current.
Why does a LazyInitializationException occur?
Because a lazy association is a proxy or an uninitialised collection that can load its data only through the persistence context that produced it. When the transaction ends, a transaction-scoped context closes and its entities become detached; if code later touches order.getLines(), typically in a REST mapper, JSON serialiser or view template, the provider has no session to issue the SELECT and Hibernate throws LazyInitializationException. The fix is to decide what each use case needs and fetch it inside the transaction, with JOIN FETCH, an entity graph or a DTO projection. Switching associations to EAGER or enabling open-session-in-view hides the symptom but causes N+1 queries and long-held connections.
What are the risks of merging detached entities from a web layer?
merge copies every field of the detached object onto the managed entity, so whatever the web layer did not populate overwrites the database. A DTO mapped to an entity without, say, creditLimit or the lines collection will set that column to null or, with orphanRemoval, delete the child rows. Concurrent edits are a second risk: two users load the same order, both submit, and the later merge silently wins unless the entity has @Version and the client sends the version back. Merging client-supplied graphs can also let callers change fields they should not, such as status or ownerId. The safer pattern is to load, validate, apply explicit changes and rely on @Version.
What happens if you call remove on a detached entity?
remove requires a managed instance, so passing a detached one throws IllegalArgumentException even though the entity has a valid id. The context cannot know whether the detached object reflects the current row, and removal must cascade and fire @PreRemove on managed state. The usual fix is to load first, for example em.remove(em.find(Order.class, id)), or to use getReference for a lighter proxy, and to handle the case where the row no longer exists. For set-based deletes, a bulk JPQL DELETE avoids loading but bypasses callbacks, cascades and the context. Spring Data's delete(entity) hides the rule by merging first, which surprises people moving to plain JPA.
Where should entity lifecycle boundaries lie in a layered application?
I put the boundary at the transactional service method. Inside it, entities are loaded, changed and flushed, and lazy associations are available because the context is open. Everything above it, REST resources, message listeners and views, works with DTOs or records that are built inside the transaction and contain exactly what the use case needs. That keeps lazy loading, dirty checking and merge semantics out of controllers, and makes the transaction scope visible in one layer. I disable open-session-in-view, map input to explicit commands applied to loaded entities, and use projections or read-only queries for read paths, so no code outside the boundary depends on managed state.
How does lifecycle design affect API and microservice boundaries?
Entities are an internal persistence model, so they should never be the contract a service publishes. If a REST API or event serialises entities, lazy loading fires queries during serialisation, bidirectional associations create cycles, and renaming a column becomes a breaking change for every consumer. I publish versioned DTOs or event schemas owned by the service and map to and from entities inside the transactional boundary. That lets the data model evolve, keeps each aggregate's lifecycle and consistency rules inside one service, and turns cross-service relationships into ids rather than object references. Changes across services then travel through APIs or events, typically with an outbox, never through shared entities or a shared schema.
Test your knowledge on this topic →Flashcards from this topic's 8 questions, filtered by level and type.