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 anEntityManager
injected by@PersistenceContext
.MyMdb.java
: an MDB that listens on a queue.MyMdb
usesMyDao
by injection with@EJB
.
One single execution of MyMdb.onMessage()
needs to perform several accesses to the database, both read and write.
- On the one hand, this makes me think that a
@Stateless
bean is not the right choice forMyDao
: theEntityManager
instance inMyDao
could be randomly accessed by different executions ofMyMdb.onMessage()
, leading threads to interfere with each other. - On the other hand, JPA documentation says that the injected
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?