Question

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.

Was it helpful?

Solution

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.

OTHER TIPS

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)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top