Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

JPA entities move among four states relative to a persistence context: new, managed, detached, and removed. The key practical distinction is that lifecycle methods first change an entity’s relationship to the persistence context; database writes usually occur later, when that context flushes. In Jakarta Persistence 4.0, the current specification describes these states in section 3.6; the 4.0 materials are milestone pages, so check the version used by your application when relying on version-specific details.

The four JPA entity lifecycle states

“Managed” is not a global property of a Java object. It means that the object is associated with a particular persistence context, which tracks its persistent state.

State Meaning What happens to field changes?
New (transient) The instance has no persistent identity and is not associated with a persistence context. Changes are not automatically synchronized.
Managed The instance has persistent identity and is currently associated with a persistence context. The context tracks changes and synchronizes them when it flushes.
Detached The instance has persistent identity but is no longer associated with the context that managed it. Subsequent changes are not automatically synchronized by that context.
Removed The instance is associated with the context but marked for deletion. The context schedules its database record for deletion at or before commit through flush.

These definitions are from the Jakarta Persistence 4.0 specification, section 3.6: Jakarta Persistence 4.0 specification.

How entities move between states

The lifecycle is easiest to understand as transitions driven by EntityManager operations and context boundaries:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
  • New → managed: call persist().
  • Managed → removed: call remove().
  • Managed → detached: call detach(), clear(), or end the persistence context.
  • Detached → managed copy: call merge() and use the object it returns.
  • Removed → managed: calling persist() on a removed entity can undo its removal.
  • Managed → managed with database values: call refresh(), which reloads state and discards pending in-memory changes.

Rollback is an important boundary too: entities that were managed or removed before the rollback become detached, so do not assume their Java-side state still reflects the database afterward.

What each lifecycle operation does

Operation Accepted input state Java object result Database effect and timing Transaction and cascade considerations Effect on pending in-memory changes
persist(entity) Use for new entities; can also restore a removed entity. Detached input is not the normal reattachment path. The argument becomes managed; the method does not return a replacement object. Schedules insertion for synchronization; SQL need not execute at the call. Transaction-scoped contexts generally require a transaction. PERSIST and ALL cascades propagate to related entities. Preserves the argument’s state as it becomes managed.
merge(entity) New or detached input; removed input is illegal or may fail at flush. Returns a distinct managed instance. The input itself does not become managed merely because it was passed to merge. Copies state into an existing managed entity or creates a managed copy; synchronization follows at flush. Transaction-scoped contexts generally require a transaction. MERGE and ALL cascades can copy state through related entities. Copies the input state to the managed target; the input remains distinct.
remove(entity) Managed input. New and already removed instances are ignored; detached input may raise IllegalArgumentException or fail later. The managed argument is marked removed. Schedules deletion, with SQL execution tied to flush and transaction completion. Transaction-scoped contexts generally require a transaction. REMOVE and ALL cascades propagate deletion. Marks the entity for deletion rather than overwriting database data with edits.
refresh(entity) Managed input; invalid for new, detached, or removed entities. Reloads database state into the managed argument. Reads the row from the database; it is not an insert or update operation. Transaction-scoped contexts generally require a transaction. REFRESH and ALL cascades propagate refresh. Overwrites unsaved in-memory changes with database state.
detach(entity) A managed entity. Removes that instance from the persistence context; it becomes detached. Stops that context from automatically synchronizing later changes. Detaching a removed entity cancels its scheduled deletion. DETACH and ALL cascades can propagate detachment. Preserves the Java object’s current values, but later edits are no longer tracked.

The operation details and state transitions follow the specification’s lifecycle rules and the EntityManager API documentation: Jakarta Persistence specification, EntityManager API, and EntityManager.merge API.

Persist versus merge: choose by state, not by intuition

Use persist for a new entity

For a newly created entity, persist() makes that same instance managed. The provider schedules it for insertion when the persistence context synchronizes. Passing a detached object to persist() is not the usual way to reattach it; use merge() when detached state needs to be copied into a managed instance.

Use merge when state must be copied

merge() is not an “attach this exact object” operation. It copies state from its argument to a managed instance and returns that managed instance. The managed target may already exist in the context or may be a newly created copy. For new input, the returned object is a new managed copy; for detached input, it has the same persistent identity but a distinct Java object identity.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Order managedOrder = entityManager.merge(detachedOrder);
// Continue working with managedOrder, not detachedOrder.

Forgetting to use the returned value is a common source of confusion: changes made afterward to the detached argument are not automatically tracked by the persistence context.

Why an entity becomes detached

An entity may be detached even though its Java object still exists and still contains an identifier. Detachment means the persistence context no longer manages it, not that the object has been deleted.

Rank #4
Sale
Java Persistence With Hibernate
  • Used Book in Good Condition
  • entityManager.detach(entity) detaches one managed instance.
  • entityManager.clear() detaches all entities currently managed by that context.
  • Closing or destroying the persistence context ends its management of entities.
  • Rolling back a transaction can detach instances that had been managed or removed.

After detachment, changing a field changes the Java object only. To persist those changes, merge the detached entity and continue with the returned managed instance.

When flush, commit, and rollback matter

Lifecycle calls generally update the persistence context first. The context synchronizes changes with the database at flush; the specification does not require every call to issue SQL immediately. Thus, a successful persist() or remove() call does not by itself prove that the corresponding row has already been inserted or deleted.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
  • Flush: synchronizes pending context changes with the database. It may occur before transaction completion; exact SQL timing and ordering can vary within the specification’s permitted behavior.
  • Commit: completes the transaction after its changes are synchronized.
  • Rollback: cancels the transaction’s database work, but Java objects may retain values that no longer correspond to the database. Previously managed and removed instances become detached.

Transaction-scoped persistence contexts generally require a transaction for persist(), merge(), remove(), and refresh(). Consult the API and provider documentation for the transaction boundaries and exact behavior of your application.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Why refresh can erase your edits

refresh(entity) makes the database authoritative for a managed instance: it reloads the row into the object and overwrites pending, unsaved in-memory changes. If a user edited a field in memory and the application then refreshes that entity, those edits are discarded unless they were already synchronized and retained in the database.

Use refresh only when discarding local pending edits is intentional—for example, when the application needs to replace managed state with the database’s current values. It cannot be used on a new, detached, or removed entity.

How cascades affect a lifecycle operation

Cascade rules are configured per relationship, not globally. The available operations are PERSIST, MERGE, REMOVE, REFRESH, and DETACH; ALL enables all five.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
  • Use REMOVE only when deleting the parent should also delete the related entity. It can cause related rows to be deleted.
  • Use MERGE when changes to the parent’s associated graph should be copied as part of merging. A broad cascade can copy more state than intended.
  • Choose cascades around relationship ownership and aggregate boundaries: operations should propagate only where the parent is responsible for the related object’s lifecycle.

The specification defines the cascade types and their semantics in its relationship and lifecycle sections: Jakarta Persistence 4.0 specification.

Quick Recap

Practical checks for lifecycle bugs

  • If an update appears to be ignored, check whether the object is detached and whether you continued editing the object returned by merge().
  • If a delete happens later than expected, remember that remove() marks a managed entity for deletion and SQL is tied to flush and transaction completion.
  • If a refresh loses values, check whether those edits were unsaved; refresh deliberately reloads database state over them.
  • If rollback leaves an object that looks edited or removed, do not infer database state from its fields; the entity may now be detached.
  • If a parent operation unexpectedly affects related records, inspect relationship cascade settings, especially REMOVE, MERGE, and ALL.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.