The following two more methods are available for injecting EntityManagerFactory in the application fields and setter method:
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 @PersistenceUnit to inject EntityManagerFactory, add @PersistenceUnit in the field and setter method where EntityManagerFactory is to be injected. The attributes that can be specified in @PersistenceUnit are as follows:
In the unitName attribute, you specify the name of the persistence unit defined in persistence.xml. However, when the persistence unit to be used can be uniquely identified, such as when only one persistence unit is defined in the EJB-JAR and WAR or EAR, you can omit the unitName attribute. For details on the persistence unit used when the unitName attribute is omitted, see 5.11.2 Reference scope of the persistence unit name.
When you use injection, normally you need not specify the name attribute, but if you specify, EntityManager is registered in the JNDI Namespace (java:comp/env) with the name specified in the name attribute. An example of using @PersistenceUnit to inject EntityManagerFactory is as follows:
@Stateless |
When you use the DD to inject EntityManagerFactory, define the following tags in the <persistence-unit-ref> tag of the DD:
In the <persistence-unit-ref-name> tag, you specify the name with which EntityManagerFactory is registered in the JNDI Namespace. The specified name is the relative path from java:comp/env.
The JNDI registration name of EntityManagerFactory is not mandatory, but the JPA specifications recommend that the name be set under java:comp/env/persistence.
In the <description> tag, you can freely code the EntityManagerFactory references to be defined. Even if this element is specified, the specified contents do not affect the operations of the application. You can also omit this tag.
In the <persistence-unit-name> tag, you specify the name of the persistence unit defined in persistence.xml. However, when the persistence unit to be used can be uniquely identified, such as when only one persistence unit is defined in the EJB-JAR and WAR or EAR, you can omit the <persistence-unit-name> tag. For details on the persistence unit used when the <persistence-unit-name> tag is omitted, see 5.11.2 Reference scope of the persistence unit name.
In the <injection-target-class> tag of the <injection-target> tag, you specify the inject destination class. In the <injection-target-name> tag of the <injection-target> tag, you specify the field name or setter method name at the inject destination. An example of defining the <persistence-unit-ref> tag in web.xml and injecting EntityManagerFactory is as follows:
... |