How to create an EntityManager if you are not sure about the device name?

I am in a situation where I need to determine the name of an EntityManager element at runtime.

For example, I would like to do something like this:

@PersistenceContext(unitName = findAppropriateJdbcName()) EntityManager entityManager; 

However, this is not possible with annotations.

Is it possible to create an EntityManager if you are not sure what the name of the element is at runtime?

+7
java java-ee jpa java-ee-6
source share
2 answers

You can specify the name of a duration unit (PU) at run time, but this is the parameter used when creating the EntityManagerFactory , and not a separate EntityManager . See Javadoc for the Persistence class method createEntityManagerFactory() . Example:

 EntityManagerFactory emf = Persistence.createEntityManagerFactory(unitname); EntityManager em = emf.createEntityManager(); // ... 

I do this in a non-Java EE application (using Java 6 SE calls in a web application hosted on Tomcat), but I'm not sure how you do the same in a container-managed Java EE 6 application. It is possible.

+7
source share

Here you need to manually create an entityManager without using annotations via JNDI to point it to different constant units at runtime.

 public EntityManager initializeEM(String pUnitName){ Context iCtx = new InitialContext(); String lookUpString = "java:comp/env/persistence/"+pUnitName; javax.persistence.EntityManager entityManager = (javax.persistence.EntityManager)iCtx.lookup(lookUpString); return entityManager; } 
+3
source share

All Articles