The following two more methods are available for using the JNDI to look up EntityManager from the application:
However, you cannot specify the JPA definition using EJB 3.0 ejb-jar.xml with Application Server. Therefore, if you want to use the JPA in an EJB, use the method specified in point 1.
The following subsections describe the methods:
When you use @PersistenceContext to define the EntityManager references, add @PersistenceContext in the class that executes lookup.
The attributes that can be specified in @PersistenceContext are as follows:
In the name attribute, you specify the lookup name with which the application code will look up EntityManager. The specified lookup name is the relative path from java:comp/env. The lookup name of EntityManager is not mandatory, but the JPA specifications recommend that the name be set up under java:comp/env/persistence.
For @PersistenceContext the same attributes are used that are used as other attributes in 5.6.1 Method of injecting EntityManager in the application. Note that only the Stateful Session Bean can look up EntityManager in the extended scope. Also, for adding multiple @PersistenceContext in one class, you add @PersistenceContexts in the class and specify the array of @PersistenceContext as the value attribute. An example of using @PersistenceContext to look up EntityManager from SessionContext is as follows:
@Stateless |
An example of using @PersistenceContext to look up EntityManager from InitialContext is as follows:
@Stateless |
When you use the DD to define the EntityManager references, define the following tags in the <persistence-context-ref> tag of the DD:
In the <persistence-context-ref-name> tag, specify the lookup name with which the application code will look up EntityManager. The specified lookup name is the relative path from java:comp/env. The lookup name of EntityManager is not mandatory, but the JPA specifications recommend that the name be set under java:comp/env/persistence.
For the <persistence-context-ref> tag, the same tags are used that are used as other tags in 5.6.1 Method of injecting EntityManager in the application. However, when EntityManager is obtained with the JNDI lookup, you cannot specify <injection-target>. Note that only the Stateful Session Bean can look up EntityManager in the extended scope.
An example of defining <persistence-context-ref> in web.xml is as follows:
... |