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

后端 未结 3 1093
梦毁少年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:22

    Well, personally, I wouldn't like to have to pass the Entity Manager to all my POJOs in my constructors or methods. Especially for non-trivial programs where the number of POJOs is large.

    I would try to create POJOs/HelperClasses that deal with the Entities returned by the EntityManager, instead of using the entitymanager directly.

    If not possible, I guess I'd create a New EJB Bean.

    0 讨论(0)
  • 2020-12-29 01:27

    I've been using helper methods and passed the EntityManager there, and it is perfectly OK.

    So I'd recommend either passing it to methods whenever needed, or make the helper a bean itself, inject it (using @EJB) and inject the EntityManager there as well.

    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题