Java Reference
In-Depth Information
Container-managed entity manager
In the Java EE environment, the container manages the entity manager. The entity
manager can be injected into a session bean, servlet, or JSP using dependency
injection with the
@PersistenceContext
annotation, as shown next:
@PersistenceContext
public EntityManager em;
Alternatively, the entity manager can be looked up using JNDI in the environment
referencing context:
@PersistenceContext(name="CatalogEM", unitName="em")
@Resource
SessionContext ctx;
EntityManager em = (EntityManager)ctx.lookup("CatalogEM");
We shall be using the simpler of the two methods—the dependency injection
method. Transactions define when entities are synchronized with the database.
Container-managed entity managers always use JTA transactions, the transactions of
the Java EE server.
Application-managed entity manager
In a Java SE environment, the application manages the entity manager. The
entity manager is created using the
createEntityManager()
method of the
EntityManagerFactory
class. An
EntityManagerFactory
object is obtained from
the
Persistence
class using a persistence unit defined in the
persistence.xml
ile
(the
persistence.xml
is still required):
EntityManagerFactory emf =Persistence.createEntityManagerFactory("
pu");
EntityManager em = emf.createEntityManager();
.....
emf.close();
emf.close();
The entity manager factory and the entity manager are required to be explicitly
closed, as the container is not managing the entity manager. In a Java EE
environment, an application-managed entity manager can be obtained by injecting
an
EntityManagerFactory
instance using dependency injection and the
@PersistenceUnit
annotation and subsequently obtaining the entity manager from
the
EntityManagerFactory
object. The
@PersistenceUnit
annotation can only be
used in a session bean, servlet, or JSP.
@PersistenceUnit
EntityManagerFactory emf;
Search WWH ::
Custom Search