I am new to the EJB and hibernate, and the following confuses me because there seems to be contradiction whenever i search for the definite answer. Question:
Is it thread-safe to inject Entity manager directly into stateless bean in the following way?
@Stateless
public class SomeBean implements SomeInterface {
//..
@Inject
private EntityManager entityManager;
//... non related transaction1()
//... non related transaction2()
Would each stateless bean have its own instance of EntityManager
or shared instance could be injected?
According to Hibernate docs:
An EntityManager
is an inexpensive, non-thread-safe object that should be used once, for a single business process, a single unit of work, and then discarded.
Does an EJB container make it thread safe?
And according to the EJB docs, stateless session beans are inherently thread safe by not allowing different clients operate on same bean at the same time.
However, I have read examples in which EntityManagerFactory
should be injected instead of EntityManager
and if EntityManager
is injected directly it should be done in Stateful bean.
Would it be safe to always inject EJB directly into Stateless bean like shown above or what would be use case when it wouldn't work?
Would each stateless bean have its own instance of EntityManager or shared instance could be injected ?
None of both. The @Inject
(and @PersistenceContext
and @EJB
) injects a proxy instance, not the actual instance.
The proxy will on every method call delegate to the right available instance in the current thread and context. In other words, the container worries about this all, not you.