Search code examples
javahibernatejpajbossjndi

EntityManager JNDI Lookup


What is the correct JNDI string to look up this persistence unit JPA-DB that is shown on JBoss 6 Startup here:

10:26:09,847 INFO  [PersistenceUnitDeployment] Starting persistence unit persistence.unit:unitName=tpar.ear/tpar-jboss-ejb3.jar#JPA-DB
10:26:09,847 INFO  [Ejb3Configuration] Processing PersistenceUnitInfo [
        name: JPA-DB
        ...]        
10:26:09,847 WARN  [Ejb3Configuration] Persistence provider caller does not implement the EJB3 spec correctly.PersistenceUnitInfo.getNewTempClassLoader() is null.
...
...
10:26:10,950 INFO  [NamingHelper] JNDI InitialContext properties:{java.naming.factory.initial=org.jnp.interfaces.NamingContextFactory, java.naming.factory.url.pkgs=org.jboss.naming:org.jnp.interfaces}
10:26:10,950 INFO  [NamingHelper] Creating subcontext: persistence.unit:unitName=tpar.ear
10:26:10,950 INFO  [SessionFactoryObjectFactory] Bound factory to JNDI name: persistence.unit:unitName=tpar.ear/tpar-jboss-ejb3.jar#JPA-DB
10:26:10,950 INFO  [NamingHelper] JNDI InitialContext properties:{java.naming.factory.initial=org.jnp.interfaces.NamingContextFactory, java.naming.factory.url.pkgs=org.jboss.naming:org.jnp.interfaces}        

I have tried the following and various others that I don't remember now and they all throw the NameNotFoundException:

entityManager = (EntityManager) jndi.lookup("java:/EntityManagers/JPA-DB");
entityManager = (EntityManager) jndi.lookup("java:comp/EntityManagers/JPA-DB");
entityManager = (EntityManager) jndi.lookup("java:comp/env/JPA-DB");
entityManager = (EntityManager) jndi.lookup("JPA-DB");

Solution

  • I was able to find the name by looking at the JNDI Tree view:

    1. Go to http://localhost:8080/jmx-console
    2. Search for JNDIView and click the link service=JNDIView
    3. Invoke button for the list() method.
    4. Search for the persistence name on the result tree view.

    It looks like this:

    Global JNDI Namespace
    
    +- persistence.unit:unitName=tpar.ear (class: org.jnp.interfaces.NamingContext)
      |   +- tpar-jboss-ejb3.jar#JPADB (class: org.hibernate.impl.SessionFactoryImpl)
    

    Though, the object is actually a SessionFactoryImpl and not an EntityManager. Additionally, the jndi lookup string generated by JBoss is hideous:

    jndi.lookup("persistence.unit:unitName=tpar.ear/tpar-jboss-ejb3.jar#JPADB");
    

    By adding the following property to the persistence.xml, I can look up using a shorter name while getting the object as an EntityManager at the same time:

    <property name="jboss.entity.manager.jndi.name" value="tpar/entity-manager"/>
    

    Note that using the long JNDI name still returns SessionFactoryImpl object in case anyone wants a SessionFactory.