2.7.3. Persistence Context

A persistence context is a set of entities such that for any persistent identity there is a unique entity instance. Within a persistence context, entities are managed. The EntityManager controls their lifecycle, and they can access datastore resources.

When a persistence context ends, previously-managed entities become detached. A detached entity is no longer under the control of the EntityManager, and no longer has access to datastore resources. We discuss detachment in detail in Entity Lifecycle Management. For now, it is sufficient to know that detachment has two obvious consequences:

  1. The detached entity cannot load any additional persistent state.

  2. The EntityManager will not return the detached entity from find, nor will queries include the detached entity in their results. Instead, find method invocations and query executions that would normally incorporate the detached entity will create a new managed entity with the same identity.

Note

OpenJPA offers several features related to detaching entities. See Detach and Attach in the Reference Guide. Defining the Detached Object Graph in particular describes how to use the DetachState setting to boost the performance of merging detached entities.

Injected EntityManagers have a transaction persistence context, while EntityManagers obtained through the EntityManagerFactory have an extended persistence context. We describe these persistence context types below.