It seems that the Entity Manager instance jboss manages and provides is a proxy to the actual implementation bound to a persistence context.
This actual implementation gathers the isolation provided by JTA transactions (per transaction contexts).
That makes me think I don’t need to worry about concurrency issues when dealing with the proxy instance.
Maybe I can even cache this proxy instance if I decide to bring it from JNDI lookups instead of container injection?
Is that reasonable?
The container is responsible for scanning for
@PersistenceContextannotations and injection ofEntityManagers. It can proxy the instances ofEntityManager.In EJB, where the container is responsible for dependency injection, you can be sure that you’re thread-safe. The persistence context will be shared between multiple components within the same transaction.
However, if you inject this
EntityManagerusing@PersistenceContextin Servlets environment (where the concurrency is a concern), you’re not thread-safe. You should use@PersistenceUnitinstead. You can refer to this part of the JBoss 7 JPA Reference Guide:Some time ago I’ve summed up what I know about Persistence Context sharing between JTA transactions and proxying of
EntityManagersby the container and published it here. I hope you’ll find it useful.