Show TOC Start of Content Area

Procedure documentation Obtaining an Entity Manager Instance  Locate the document in its SAP Library structure

Use

JPA provides the Entity Manager API (EM), which is the main API for application developers to interact with the database. The EM manages the life cycle and state of entities. It supports create, read, update, and delete (CRUD) operations, finding entities, persisting entities, query execution, and so on.

Prerequisites

An EM instance is associated with a Persistence Context. The Persistence Context defines the scope under which entity instances are managed by the EM. The Persistence Context represents a set of managed entity instances in a data store. There are two types of Persistence Contexts:

      A transaction-scoped Persistence Context ends when the transaction ends.

      An Extended Persistence Context may span multiple transactions and ends when it is explicitly closed by the container or by the application.

The EJB container supports container-managed and application-managed EMs. The following table summarizes the differences between them:

 

Container-Managed

Application-Managed

Life cycle

Managed by the container.

Managed by the application.

EM and Persistence Context created and destroyed explicitly by the application.

Persistence Context

Propagated by the container to all application components that use the EM instance within a single JTA transaction.

Not propagated across application components. Each EM creates a new, isolated Persistence Context.

Transaction Control

Provides only JTA transaction control.

Provides JTA and non-JTA transaction control.

EM instance

Obtained using dependency injection.

Obtained from factory.

Procedure

...

       1.      To obtain a container-managed EM instance, you use the @PersistenceContext annotation to have the EJB container inject an EM instance into the application component using dependency injection:

Example

 @PersistenceContext

 public EntityManager em;

       2.      To obtain an application-managed EM instance, you must first obtain an entity manager factory instance:

Example

@PersistenceUnit

EntityManagerFactory emf;

EntityManager em = emf.createEntityManager();

Result

The container injects an entity manager instance into the application component. You can use the entity manager instance to perform operations in entity instances.

End of Content Area