🗃️ JPA Q57 / 63

What is the difference between flush() and clear() in JPA?

AI-Powered Answer ✓ Answered

In JPA, both `EntityManager.flush()` and `EntityManager.clear()` interact with the persistence context, but they serve fundamentally different purposes related to synchronizing state with the database and managing entity lifecycle.

`EntityManager.flush()`

flush() is a method that synchronizes the current state of the persistence context with the underlying database. It writes all pending changes (insertions, updates, deletions) from the managed entities in the persistence context to the database.

It's important to note that flush() does not commit the transaction; it merely ensures that the database reflects the current state of the entities within the persistence context. The actual database commit happens when the transaction is committed.

  • Synchronizes the persistence context with the database.
  • Does not end the transaction or clear the persistence context.
  • Entities remain in the managed state after a flush.
  • Can be invoked explicitly or implicitly (e.g., before executing a query that might need the latest data, or at transaction commit).

`EntityManager.clear()`

clear() is a method that detaches all managed entities currently held within the persistence context. After clear() is called, all entities that were previously managed by this EntityManager become detached.

Detached entities are no longer associated with any persistence context. Changes made to detached entities will not be automatically persisted to the database. To re-associate a detached entity with a persistence context, it must be merged back using entityManager.merge().

  • Detaches all entities from the persistence context.
  • The persistence context becomes empty.
  • All pending changes that have not been flushed are lost.
  • Useful for freeing up memory and preventing stale data issues when working with a large number of entities.

Comparison Table

Featureflush()clear()
PurposeSynchronizes persistence context with database.Detaches all entities from persistence context, making it empty.
Impact on ContextEntities remain managed within the context.All entities become detached; context is emptied.
Data PersistenceWrites pending changes to the database.Discards pending changes if not flushed beforehand.
Entity StateEntities remain in a managed state.Entities transition to a detached state.
Memory UsageDoes not significantly reduce memory usage of the context itself.Frees up memory associated with the managed entities.