Is it okay to pass injected EntityManagers to EJB bean's helper classes and use it?

后端 未结 3 1118
梦毁少年i
梦毁少年i 2020-12-29 01:02

We have some JavaEE5 stateless EJB bean that passes the injected EntityManager to its helpers.

Is this safe? It has worked well until now, but I found out some Ora

3条回答
  •  一个人的身影
    2020-12-29 01:35

    I used a similar pattern, but the helper was created in @PostConstruct and the injected entity manager was passed in the constructor as parameter. Each EJB instance had its own helper and thread-safety was guaranteed then.

    I also had a variant were the entity manager was not injected (because the EJB wasn't using it altogether), so the helper has to look it up with InitialContext. In this case, the Persistence context must still be "imported" in the parent EJB with @PersistenceContext:

    @Stateless 
    @PersistenceContext(name="OrderEM") 
    public class MySessionBean implements MyInterface { 
      @Resource SessionContext ctx; 
      public void doSomething() { 
         EntityManager em = (EntityManager)ctx.lookup("OrderEM"); 
         ... 
      } 
    }
    

    But it's actually easier to inject it (even if the EJB doesn't use it) than to look it up, especially for testability.

    But to come back to your main question, I think that the entity manager that is injected or looked up is a wrapper that forwards to the underlying active entity manager that is bound to the transaction.

    Hope it helps.

    EDIT

    The section § 3.3 and § 5.6 in the spec cover a bit the topic.

提交回复
热议问题