Java 当您不确定单元名称时,如何创建 EntityManager?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4292969/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-14 15:28:05  来源:igfitidea点击:

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

javajpajakarta-eejpa-2.0java-ee-6

提问by Brian DiCasa

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

我处于需要在运行时确定 EntityManager 的单元名称的情况。

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?

当您在运行时不确定单元名称是什么时,是否可以创建 EntityManager?

回答by Jim Tough

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 Javadocfor the Persistenceclass method createEntityManagerFactory(). Example:

可以在运行时指定持久性单元 (PU) 名称,但这是用于创建 的参数EntityManagerFactory,而不是单个EntityManager. 请参阅Javadoc中Persistence类方法createEntityManagerFactory()。例子:

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.

我在非 Java EE 应用程序中执行此操作(在 Tomcat 托管的 Web 应用程序中使用 Java 6 SE 调用),但我不确定您如何在容器管理的 Java EE 6 应用程序中执行相同的操作。有可能的。

回答by Nayan Wadekar

Here you have to manually create entityManager without using annotations through JNDI to point it to different persistent unit at runtime.

在这里,您必须手动创建 entityManager,而无需通过 JNDI 使用注释在运行时将其指向不同的持久单元。

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;
}