How do you create an EntityManager when you are unsure of the unit name?

試著忘記壹切 提交于 2019-11-28 03:36:13

问题


I'm in a situation where I need to determine the EntityManager's unit name at run time.

For example, I'd like to do something like this:

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

However, this is not possible with annotations.

Is it possible to create the EntityManager when your not sure of what the unit name is until run time?


回答1:


It is possible to specify the persistence unit (PU) name at runtime, but this is a parameter used in the creation of the EntityManagerFactory, not an individual EntityManager. See the 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 Tomcat-hosted web app) but I'm not sure how you do the same thing in a container-managed Java EE 6 application. It is possible.




回答2:


Here you have to manually create entityManager without using annotations through JNDI to point it to different persistent unit 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;
}


来源:https://stackoverflow.com/questions/4292969/how-do-you-create-an-entitymanager-when-you-are-unsure-of-the-unit-name

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!