I am running a plain Java application (JAVA SE) and wanted to have method based transactions support and being able to inject the entity manager.
I have followed the example in http://seamframework.org/Documentation/WeldAndJPARunningInTomcat
but in my opinion this approach is not correct.
First of all the interceptor does not close the entity manager once an exception has happened. Second, the entity manager will be injected from an application scope what is most likely not what you want.
Which entity manager is used should be driven by the wanted transaction type as well, 'requires new' should get always a fresh entity manager injected.
Technically, I have achieved this by injecting a delegate class which implements the EntityManager interface. It gets the current EntityManager from a thread local. The transaction interceptor is responsible to add the entity manager to the thread local and to remove it from there.
I noted my findings in an article http://www.laliluna.de/articles/2011/01/12/jboss-weld-jpa-hibernate.html . I have implemented only 'requires new' semantic but the example can be easily extended to 'require transaction' semantic to leave an existing entity manager and pass it to other beans as well.
My example is missing a solution for a entity manager which is bound to the scope of the bean it is injected in. May be an approach like @Transaction(
inherit) could be the semantic but I am not sure, how to store the EntityManager in that case.
I appreciate your feedback on this.
Best Regards / Viele Grüße