views:

391

answers:

2

When using EntityManager, is it better to get one instance with PersistenceContext and pass it around in my program, or should I use dependency injection more than once?

In my application each client will communicate with a stateful session bean, and each bean needs to use EntityManager at some point. I guess that bean methods are invocated concurrently (but I'm not even sure). How do I guarantee that I use EntityManager in a thread-safe manner? With transactions? With a separate instance in each bean?

Sorry if this is confusing, I'm new to EJB/JPA and I couldn't find any material which addresses my questions.

+2  A: 

Use @PersistenceContext to inject your EntityManager in your DAO class(es). These are the classes that will handle the database operations. Then in all other (service) classes inject your DAO class(es). Your DAO should be a stateless bean (no need of a remote interface, only local)

Bozho
Thanks for your answer. Why should the DAO be a stateless bean?
Bastien Léonard
It doesn't need a state. What should be stored in it?
Bozho
+1  A: 

Yes, you should inject the EntityManager instances (which will be different for each thread/client request) into your stateful session beans (which are not invoked concurrently, at least not from different clients).

There is no point in creating DAO classes, though. JPA already is a high-level persistence API that gives you RDBMS independence and portability between different JPA implementations. So, DAOs would only add clutter to the codebase.

For transactions, you don't really need to do anything. Business methods in session beans have a "Required" transaction attribute by default, so they will always run inside a client-specific transaction.

Rogerio
Thanks for your answer. So my stateful bean should have an `EntityManager` attribute, and pass it by parameter to any other object which will access the DB?
Bastien Léonard
Yes, if needed. But when using EJBs, it would be best to only access the EntityManager API from the session beans themselves (stateless or stateful); then you will never need to pass the EntityManager instance around. Of course, other kinds of managed beans (like MDBs) also could do the same.
Rogerio