I'm developing a system to process messages and update the database accordingly, but I need to keep some degree of isolation between layers. I have in mind something like the following.
MyDao.java
: a @Stateless
bean that provides database access. MyDao
accesses the database using JPA, with an EntityManager
injected by @PersistenceContext
.MyMdb.java
: an MDB that listens on a queue. MyMdb
uses MyDao
by injection with @EJB
.One single execution of MyMdb.onMessage()
needs to perform several accesses to the database, both read and write.
@Stateless
bean is not the right choice for MyDao
: the EntityManager
instance in MyDao
could be randomly accessed by different executions of MyMdb.onMessage()
, leading threads to interfere with each other.EntityManager
is just a proxy: the actual persistence context on which it operates is the one bound to the JTA transaction. This way everything should be ok because, even though EntityManagers are "shared", each MDB will have a different transaction ongoing and thus work in safe isolation.What is the right scenario? Am I missing something?
Entity managers injected in a stateless EJB in the way that you described are exactly what you should do. This type of injection provides a 'Container-Managed Entity Manager' which is 'transaction scoped'. So in the scenario that you describe.
The specific type of injected entity manager for the same EJB instance doesn't survive and is not re-used across different transactions.