EntityTransactionInterceptor with correct EntityManager in J2SE
awestwel Mar 15, 2010 5:52 PMHey Everyone
I wanted to get some clarification regarding the example show at http://seamframework.org/Documentation/WeldAndJPARunningInTomcat
1. Created a class to produce my EntityManager
public class PersistenceProducer { @Produces @TicketManager @PersistenceContext(unitName="LogicBoxTicketManager") EntityManager entityManager; }
2. Create a manager class(Singleton) with a simple qualifier named TicketManager
@Singleton @Named("TestManager") public class TestManager { @Inject @TicketManager EntityManager entityManager; @Transactional public void persist(TestBean testBean) { entityManager.persist(testBean); } }
3. Added source for the EntityTransactionInterceptor (which I know is being called) and the transactional qualifier
@Transactional @Interceptor public class EntityTransactionInterceptor { private @Inject @Any EntityManager entityManager; @AroundInvoke public Object aroundInvoke(InvocationContext invocationContext) throws Exception { boolean active = !(entityManager.getTransaction().isActive()); if(active) { entityManager.getTransaction().begin(); } try { Object result = invocationContext.proceed(); if(active) { entityManager.getTransaction().commit(); } return result; } catch (Exception exception) { if (active) entityManager.getTransaction().rollback(); throw exception; } } }
My question is in regards to the EntityTransactionInterceptor. How does it know to use the instance of the EntityManager defined in the TestManager and not to create a new one? I understand the @Inject basics but how does the Interceptor know which EntityManager to inject? Especially with mine containing another qualifier @TicketManager?
The reason I ask is the sample code runs fine but no record is added to the database. I am assuming this is because it is not getting the correct EntityManager from the TestManager class. If I remove the @Transactional from the persist method and add the following lines around the persist method it works fine.
-> entityManager.getTransaction().begin(); entityManager.persist(auditTypeBean); -> entityManager.getTransaction().commit();
Thanks for the help in advanced :)