JNDI中的EntityManager

时间:2017-12-13 10:06:07

标签: jpa java-ee glassfish

我需要在同一个Web应用程序中使用不同的数据库,因此我无法使用persistent.xml来定义目标数据库。数据库随连接的客户端而变化。 我发现了这个:

public EntityManager getEntityManager() {
    if (em == null}
        try{
            em = (EntityManager)(new InitialContext())
                                        .lookup("java:comp/ejb/EntityManager");
        } catch (Exception e){};
    }
    return em;
}

在此网址:http://wiki.eclipse.org/EclipseLink/Examples/JPA/EMAPI

我的问题是:如何在GlassFish的JNDI中记录EntityManager或持久性单元?

1 个答案:

答案 0 :(得分:0)

假设我的persistence.xml是:

<persistence version="2.1" xmlns="http://xmlns.jcp.org/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd">

 <persistence-unit  name="ctx-vendor" transaction-type="JTA">
   <provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
 </persistence-unit>
</persistence>

我们有两个用例:

WAR application WEB-INF/web.xml file

<persistence-context-ref>
  <description>JNDI for lookup EntityManager</description>
  <persistence-context-ref-name>persistence/ctx-vendor</persistence-context-ref-name>
  <persistence-unit-name>ctx-vendor</persistence-unit-name>
  <persistence-context-type>Transaction</persistence-context-type>
</persistence-context-ref>

EAR application META-INF/application.xml file:

<application xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/application_7.xsd"
  version="7">
  <description>My Vendor System</description>
  <display-name>vendor-ear</display-name>
  <module>
    <web>
      <web-uri>vendor-rest.war</web-uri>
      <context-root>/vendor-rest</context-root>
    </web>
  </module>
  <module>
    <ejb>vendor-service.jar</ejb>
  </module>
  <library-directory>lib</library-directory>
  <persistence-context-ref>
    <description>JNDI for lookup EntityManager</description>
    <persistence-context-ref-name>persistence/ctx-vendor</persistence-context-ref-name>
    <persistence-unit-name>ctx-vendor</persistence-unit-name>
    <persistence-context-type>Transaction</persistence-context-type>
  </persistence-context-ref>
</application>

无状态会话Bean

@PersistenceContext(name = "persistence/ctx-vendor", unitName = "ctx-vendor")
public class BaseFacade
{ }

@Stateless
@Local(CatalogFacade.class)
public class CatalogFacadeImpl extends BaseFacade implements CatalogFacade
{
}

在Glassfish 4.1中进行了测试