users@glassfish.java.net

Re: Surprising JPA (Toplink) Behaviour (glassfish v1 UR1)

From: <glassfish_at_javadesktop.org>
Date: Tue, 27 Mar 2007 12:26:23 PST

Hi Koen,

ThreadLocal is not an API that should be used by application code to pass context around.
If you need access to a container-managed EntityManager from code other than the ejb
bean class itself you can always retrieve the same dependency from its component
environment. Any Class, Field, or Method-level Java EE environment annotation always
corresponds to an entry within the component environment in which it is declared.
If the case of field annotation, the dependency name is specified by either the name()
attribute or defaults to <fully-qualified-declaring-class-name>/<field name>.

So, given your example, any other utility code running within the scope of the SLSB
invocation would retrieve the container-managed entity manager as follows :

   EntityManager em = (EntityManager) new InitialContext().lookup
         ("java:comp/env/<fully-qualified-declaring-classname>/em");

Providing the name() attribute when declaring the dependency makes things easier :
@PersistenceContext(name="myem_ref", unitName="default")

then the lookup is :

   EntityManager em = (EntityManager) new InitialContext().lookup("java:comp/env/myem_ref");
[Message sent by forum member 'ksak' (ksak)]

http://forums.java.net/jive/thread.jspa?messageID=210167