I have recently moved to Java EE (Wildfly) and I'd like to lookup an EntityManager
from JNDI. At present I am defining a datasource in my standalone.xml and successfully retrieving this via JNDI but this provides me with only the Datasource and not an Entity Manager.
I am aware that I can create a persistence.xml and use @PersistenceContext
but I am really looking at a way to avoid compile time knowledge of the JNDI name, so instead want to perform a lookup based on runtime information to retrieve the appropriate Entity Manager.
Unfortunately a persistence unit, from which an entity manager is derived can not be defined in a portable way without using a persistence.xml
file.
If this is important for you please consider voting for JPA_SPEC-114 and additionally providing a comment there.
You can, more or less, make the persistence unit independent of the final JNDI name by using a resource-ref. A resource-ref does causes your code to become dependent on a container specific mechanism to switch what the resource-ref
is pointing to.
An alternative, with its own cons unfortunately, is using a switchable data source approach. You can then define a data source using a fixed JNDI name and reference that from a persistence.xml
file, and then use whatever method your switchable data source uses internally to go to the actual data source. This can then be either directly a data source implementation (such as shown in the link) or perhaps fetching another data source from JNDI (which effectively does what resource-ref does, but then using your own mechanism to switch)