The persistence context is the first-level cache where all the entities are fetched from the database or saved to the database.

Persistence context keeps track of any changes made into a managed entity. If anything changes during a transaction, then the entity is marked as dirty. When the transaction completes, these changes are flushed into persistent storage.

The EntityManager is the interface that lets us interact with the persistence context. Whenever we use the EntityManager, we are actually interacting with the persistence context.

This is the most common way to inject an entity manager:

@PersistenceContext
private EntityManager entityManager;

What gets injected in the spring bean is not the entity manager itself but a context aware proxy that will delegate to a concrete entity manager at runtime. Usually the concrete class used for the proxy is SharedEntityManagerInvocationHandler, this can be confirmed with the help a debugger.

Here we are by default in “Entity Manager per transaction” mode. In this mode, if we use this Entity Manager inside a @Transactional method, then the method will run in a single database transaction.

An extended persistence context can span across multiple transactions. To tell EntityManager to use extended-scoped persistence context, we need to apply the type attribute of @PersistenceContext:

@PersistenceContext(type = PersistenceContextType.EXTENDED)
private EntityManager entityManager;

Resources