In Tapestry there are (mainly) two ways to obtain an EntityManager
instance:
- By injecting the
EntityManager
directly:@Inject @PersistenceContext(unitName = MyPersistenceUnit) private EntityManager entityManager;
- By using the
EntityManagerManager
(which is also injected):EntityManager entityManager = entityManagerManager.getEntityManager(MyPersistenceUnit);
The EntityManagerManager
states in its javadoc that it manages one EntityManager
per thread:
Manages
EntityManager
s for the current thread. AnEntityManager
is created as needed and closed at the end of each request.The implementation of this service is per-thread.
Does this also apply for injecting the EntityManager
directly? So for example, if I start a transaction in one thread, like that:
entityManager.getTransaction().begin();
will the transaction of the EntityManager
in another thread be inactive - i.e. will entityManager.getTransaction().isActive()
be false for other threads, where the EntityManager
also was injected?
More generally I am curious about what should be used. What are the differences / advantages of one over the other?
Both approaches are equal, you can use any with same guarantees:
EntityManager
is always a per-thread instance, nothing is shared between threads. EachEntityManager
is discarded/closed at the end of each request (whenPerthreadManager#cleanup()
method is called).EntityManagerManager
is used as a source inEntityManagerObjectProvider
which produces instances ofEntityManager
so that you could simply write@Inject EntityManager
instead of obtaining it from the manager explicitly.