Show TOC

Obtaining an Entity Manager InstanceLocate this document in the navigation 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.

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:

                      @PersistenceContext
    public EntityManager em;
                   
  2. To obtain an application-managed EM instance, you must first obtain an entity manager factory instance:

                      @PersistenceUnit
    EntityManagerFactory emf;
    EntityManager em = emf.createEntityManager();
                   

More Information

Entity Manager