0 Replies Latest reply on Oct 4, 2006 6:34 PM by Erik Vandekieft

    Safety of retaining references to EntityManagers obtained vi

    Erik Vandekieft Newbie

      Hi,

      I have a question about the safety of an EJB 3.0 design pattern that I've evolved during the development of a project. It seems naive to me now in retrospect, but could someone please comment in more detail about its safety?

      I have a stateless EJB that obtains an EntityManager via the following injection:

      @PersistenceContext(unitName="pid") private EntityManager manager;


      I then have some helper POJOs that perform EJB3.0 QL queries for me, and return me results. I instantiate these pojos in an init() method marked with the @PostConstruct annotation like so:

      @PostConstruct
      public void init() {
       muHelper = new MatchUnitHelper(manager);
       jobHelper = new JobHelper(manager);
       // ... etc
      }


      Note that since this happens "post-construct", the "manager" variable has been instantiated via injection. I set things up this way so that I could easily run my stateless bean outside the container, by simply constructing it with an EntityManager obtained via the standard J2SE EntityManagerFactory pattern.

      However, while reading the Hibernate EntityManager documentation, I noted that they say that:


      If the EntityManager throws an exception (including any SQLException), you should immediately rollback the database transaction, call EntityManager.close() (if createEntityManager() has been called) and discard the EntityManager instance. Certain methods of EntityManager will not leave the persistence context in a consistent state. No exception thrown by an entity manager can be treated as recoverable. Ensure that the EntityManager will be closed by calling close() in a finally block. Note that a container managed entity manager will do that for you. You just have to let the RuntimeException propagate up to the container.


      Suppose I let an exception from the EntityManager propagate up to the container. Will JBoss then discard and replace the "manager" instance in my stateless bean, thus making all the references that I had passed to the POJOs invalid (pointing to a "dead" EntityManager?) Or is the "manager" variable a safe proxy of some sort that remains valid?

      Any help is appreciated, thanks.