5 Replies Latest reply on Mar 9, 2010 4:21 PM by pmuir

    Transaction scoped persistence contexts

    wujek

      Hi.
      When we use a Stateless Session Bean and have @PersistenceContext injected the 'old' way, each time the bean is used, say, from a servlet, the context is freshly injected.
      How does it work with CDI injection? Suppose I have a @PersistenceContext @Produces field as outlined in the specs and Weld docs - when is the @PersistenceContext actually injected into the producer field, and looked up to initialize a Stateless Session Bean? Does this happen for every JNDI lookup / @EJB / @Inject of the bean in question?


      Regards,
      Wujek

        • 1. Re: Transaction scoped persistence contexts
          pmuir

          It depends on the exact container you are using. In JBoss AS, assuming you have a dependent bean producing the peristence context, it would get looked up each time.

          • 2. Re: Transaction scoped persistence contexts
            wujek

            The bean is dependent, I tested it myself in GlassFish V3 in the meantime, and it works as described, that is, each new SLSB gets a new context.


            But, the question now is, after reading your response: is this behaviour really container specific? Is it valid for a Java EE 6 compliant container look it up only once, for example? It would mean this such a producer is useless in environments that use container managed EntityManagers, as it would provide the same instance all the time, whereas the whole point of a container managed transaction scoped entity manager is to have a fresh (not necessarily a new instance, just fresh) persistence context in each new TX. If the producer behaved this way, it simply could not be used for container managed EntityManagers injection, and going further, it would make this nice type-safe @Inject injection unusable in such scenario, which is a pretty common one. Or I simply misunderstood your post. Could you please clarify?


            Regards.

            • 3. Re: Transaction scoped persistence contexts
              pmuir

              The container must follow the rules layed out for injecting persistence contexts and resources as defined by the Java EE spec. This spec may allow the container to perform optimizations when looking up resources. Hence the vagueness of my answer.

              • 4. Re: Transaction scoped persistence contexts
                wujek

                Ok, suppose there are some optimizations, but this also means each new TX must have a fresh persistence context associated in a specs compliant implementtion. Is this correct?

                • 5. Re: Transaction scoped persistence contexts
                  pmuir

                  For non-extended persistence contexts, then yes.