I'm working on a JavaEE application which uses JPA and is deployed on JBoss/Wildfly. I have my persistence.xml and standalone.xml properly configured for JPA to recognize the datasource. I understand that the normal way to obtain a context managed EntityManager is the following:
@PersistenceContext(unitName = "foo")
EntityManager em;
However, in my usecase the application defining the datasource and the library accessing it using JPA are separate. I need a way to programmatically produce an EntityManager by its persistence unit name. I understand that the easiest way to do this is this:
Persistence.createEntityManagerFactory("foo").createEntityManager()
However, this gives me an application managed entity manager, which forces me to handle transactions myself. I want to get a context managed entity manager, where I demarcate transactions by CDI-injecting UserTransaction or in similar ways.
Is there a way to create an EntityManager at runtime and attach its transaction to the current context?
The original code worked around this by providing one global, application-scoped entitymanager. This way every occurance of EntityManager obviously has the same transaction. Besides other problems, this causes errors when trying to parallelize queries, as EntityManager is not thread safe. That's why I am currently trying to create entity manager instances ad-hoc, but keep the transaction semantics.
EntityManager, in the bean that uses the library? If the library is CDI-enabled, why not use a@Producesmethod with a custom qualifier that the library will require? Finally, why not use@PersistenceContextwithoutunitName? - crizzis