In Tapestry there are (mainly) two ways to obtain an EntityManager instance:
- By injecting the
EntityManagerdirectly:@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
EntityManagers for the current thread. AnEntityManageris 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:
EntityManageris always a per-thread instance, nothing is shared between threads. EachEntityManageris discarded/closed at the end of each request (whenPerthreadManager#cleanup()method is called).EntityManagerManageris used as a source inEntityManagerObjectProviderwhich produces instances ofEntityManagerso that you could simply write@Inject EntityManagerinstead of obtaining it from the manager explicitly.