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

Posted by Zwei steinen on Stack Overflow See other posts from Stack Overflow or by Zwei steinen
Published on 2010-03-08T07:01:11Z Indexed on 2010/03/08 7:06 UTC
Read the original article Hit count: 254

Filed under:
|
|
|

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 Oracle document that states its implementation of EntityManager is thread-safe. Now I wonder whether the reason we did not have issues until now, was only because the implementation we were using happened to be thread-safe (we use Oracle).

@Stateless
class SomeBean {
    @PersistenceContext
    private EntityManager em;

    private SomeHelper helper;

    @PostConstruct
    public void init(){
        helper = new SomeHelper(em);
    }

    @Override
    public void business(){
        helper.doSomethingWithEm();
    }

}

Actually it makes sense.. If EntityManager is thread-unsafe, a container would have to do

inercept business()
this.em = newEntityManager();
business();

which will not propagate to its helper classes.

If so, what is the best practice in this kind of a situation? Passing EntityManagerFactory instead of EntityManager?

© Stack Overflow or respective owner

Related posts about java

Related posts about jpa