Tapestry `EntityManager` vs `EntityManagerManager`

69 Views Asked by At

In Tapestry there are (mainly) two ways to obtain an EntityManager instance:

  1. By injecting the EntityManager directly:
    @Inject
    @PersistenceContext(unitName = MyPersistenceUnit)
    private EntityManager entityManager;
    
  2. 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. An EntityManager 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?

1

There are 1 best solutions below

0
On

Both approaches are equal, you can use any with same guarantees: EntityManager is always a per-thread instance, nothing is shared between threads. Each EntityManager is discarded/closed at the end of each request (when PerthreadManager#cleanup() method is called).

EntityManagerManager is used as a source in EntityManagerObjectProvider which produces instances of EntityManager so that you could simply write @Inject EntityManager instead of obtaining it from the manager explicitly.