As we can see, the persistence.xml file in the JAR file can define multiple persistence contexts with different names. To obtain an EntityManager from a named persistence context, you just need to specify the name in the unitName attribute of the @PersistenceContext annotation. The following example injects the ejb3trail persistence context to the EntityManager.
@PersistenceContext(unitName="ejb3trail")
EntityManager em;
You can omit the unitName attribute if the following conditions are met:
- You only have one persistence context defined in the
persistence.xml file in the entire application.
- You are using a scoped classloader for the application.
The second item probably needs more explanation. In a web application deployed in an EAR file, that means you need a jboss-app.xml file in the EAR file's META-INF directory. The file can specify an arbitrary name for the classloader. Here is an example:
<jboss-app>
<loader-repository>
trailblazer:app=ejb3
</loader-repository>
</jboss-app>
If you do not have a scoped classloader for the application, all the persistence contexts defined in the applications would be globally available in the entire server, and the @PersistenceContext injection look for an EntityManager in the global context as well. That allows you to use persistence context defined outside of your own application. But you also have to explicitly specify the persistence context name via the unitName attribute.