views:

174

answers:

1

According to many examples it is possible to inject an EntityManager into @Stateless or @Singleton EJBs like this:

@Stateless // or @Singleton
public class MyRepository {
   @PersistenceContext
   private EntityManager em;
   ...
}

The EJB 3.1 Spec says that dependency injection is only performed at construction time, so that all callers of MyRepository would use the same instance of EntityManager. How does the EJB container ensure that the correct EntityManager instance is used?

+2  A: 

My understanding is that a @Stateless bean will never be used by two clients concurrently; the container will simply create more instances of the same bean if it needs to serve multiple clients.

As for @Singleton beans, the spec says that by default they use Container Managed Concurrency, where the container uses method Locks and could reject clients with a timeout exception if the singleton is busy.

Edit: additionally, the @PersistentContext type is transaction-scoped by default (16.11.1.1 in the spec) so all entities managed by EntityManager are detached at the end of each transaction.

Mirko Nasato
I agree with you, although the locking in singletons can be customized. But there's another point: the injection is only performed on bean creation and then used by multiple callers (concurrently or not).
deamon
The persistence context is transaction-scoped by default.
Mirko Nasato