A container managed Persistence Context is always associated with a specific scope among the following available scopes: TRANSACTION or EXTENDED .
The more common scenario is the TRANSACTION scope, which Persistence Context definition is like the following:
@PersistenceContext(type = PersistenceContextType.TRANSACTION) private EntityManager entityManager;
Since the default Persistence Context scope is TRANSACTION , the following declaration - missing the explicit scope type definition - is equivalent to the above one:
@PersistenceContext private EntityManager entityManager;
On the other hand, an EXTENDED Persistence Context must have the explicit type definition and is declared like the following:
@PersistenceContext(type = PersistenceContextType.EXTENDED) private EntityManager entityManager;
The main difference between a transaction scoped Persistence Context and an extended Persistence Context is that the life time of a transaction Persistence Context is exactly the same as the current single transaction to which the context is associated. As soon as the current transaction ends (commit or rollback), the entities which are currently managed by the Entity Manager will immediately become detached.
The aforementioned rule does not apply to an extended Persistence Context, which duration may spawn across multiple transactions until explicitly closed by the application (or the associated EJB is removed/destroyed).
Since the extended Persistence Context has a duration that spawns multiple transactions, and consequently keeps state across multiple EJB method calls (transactional or non-transactional), it only makes sense to be used withStateful EJB's, which may be used to implement conversation style interaction with clients.
In this article we will cover the EXTENDED Persistence Context and compare it to the TRANSACTION Persistence Context, considering the following subjects:
- Loading of entities
- Lazy loading of entity relationships
- Persisting entities outside of an active transaction
- Entities directly bound to UI forms
As a side note to this article, an Application Managed Persistence Context scope is always EXTENDED (see Container vs Application Managed EntityManager ).