7 Replies Latest reply on Aug 30, 2009 5:08 PM by henk de boer

    persistence-context-ref always yields same object instance i

    henk de boer Master


      I'm experimenting a little with the different ways of programmatically obtaining an entity manager inside a servlet. I'm running Jboss 5.10 on Mac OS X 10.5.7 using JDK 6.

      I tried the approach of using a persistence-context-ref element in web.xml, basically as outlined here: http://weblogs.java.net/blog/ss141213/archive/2005/12/dont_use_persis_1.html

      My reference looks like this:


      By itself this seems to work beautifully for doing JNDI lookups in a Servlet or Filter:

      EntityManager entityManager = (EntityManager )new InitialContext().lookup("java:comp/env/persistence/test");

      The above code snippet gives me back an instance of the entity manager. However, I discovered with a debugger that this is always the same instance. Whether I do the JNDI lookup multiple times right after each other in the same method, or test what the JNDI lookup returns in multiple simultaneous requests, the result is always an object instance with the same ID (e.g. org.jboss.jpa.tx.TransactionScopedEntityManager@d78f1b).

      When I however bind the entity manager factory into the global JNDI name space using the following property in persistence.xml:

      <property name="jboss.entity.manager.factory.jndi.name" value="java:/test_pu_factory"/>

      And lookup that factory using JNDI again and then use that to create an entity manager, the instance is always different.

      As per the advice that an entity manager is not tread-safe (and thus should not be stored in an instance variable of a servlet), I wonder whether it's correct that the JNDI lookup for the entity manager bound via the persistence-context-ref element always returns the same object instance.