Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How many EntityManagers are injected for a given PersistenceContext?

Tags:

java

jpa

ejb-3.0

I am injecting EntityManager objects in stateless EJB3 beans (which act as DAO objects and each provide access to a different database table). Deployment is in JBoss AS 7.

I then added code using System.identityHashCode in the EJB3 beans methods to see the various instances of the EntityManagers injecting (hoping to see the same instance in all DAOs). E.g. like:

@Stateless
public class AFacade {
    @PersistenceContext(unitName="foo")
    EntityManager em;

    public List<A> findAll() {
         l.info("entity manager is: "+System.identityHashCode(em)+" class is: "+em.getClass().getSimpleName());
         ...
    }

However, what I noticed is that each DAO (e.g. AFacade, BFacade and so on) was injected with a different EntityManager (as reported by identityHashCode) although the PersistenceContext was the same. The implementing class was TransactionScopedEntityManager in all cases.

It is not clear to me why this different EntityManager objects are injected, whether this is something that should concern me or not. Also, I understand that the EJB3 container may actually inject proxies to the real EntityManager so these different instances may actually be proxies to a single EntityManager.

like image 879
Marcus Junius Brutus Avatar asked Feb 18 '23 11:02

Marcus Junius Brutus


1 Answers

Yes, they are proxies (in fact, I think they are thread safe decorators, rather than proxies) on the real entity managers.

I'm not sure if you know that the EntityManager is a wrapper around a connection. If you wouldn't have this decorator (or proxy), all invocations to that stateless bean would share the same connection (and potentially transaction), which is not what you want.

like image 50
Augusto Avatar answered Apr 07 '23 13:04

Augusto