An answer for those that come this way after me :)
The documentation is a bit confusing. If you look here:
http://docs.jboss.org/hibernate/stable/ ... ml#d0e2823There are some great examples of how to do it outside of a Java EE container. Documentation about 'em.createEntityManager' and 'em.getTransaction' and the JTA variant 'utx.commit()' and so forth. There is also discussion of how to look after your own EntityManager through the use of Filters or ThreadLocals or whatnot. Then there is a bit that says:
"all you have to do in a managed environment is to inject the EntityManager, do your data access work, and leave the rest to the container. Transaction boundaries are set declaratively in the annotations or deployment descriptors of your session beans. The lifecycle of the entity manager and persistence context is completely managed by the container."
And there are no further examples of JTA management. But this is misleading if you are trying to implement the (recommended) EntityManager-per-request pattern in a container-managed environment. When they say 'Transaction boundaries are set declaratively in the annotations... of your session beans' that's actually pretty useless, because it means
you will start and end a transaction with each bean call during your HTTP request.
What you really need is to start and end the transaction around the entire HTTP request, and to do that
you still need to use 'utx.commit()' and Filters and whatnot. Even if you are using container-managed persistence contexts, you'll still need a ServletFilter around your HTTP Request something like:
Code:
public void doFilter( ServletRequest request, ServletResponse response, FilterChain chain )
throws ServletException {
UserTransaction tx = new InitialContext().lookup( "java:comp/UserTransaction" );
tx.beginCurrent();
try {
chain.doFilter( request, response );
tx.commitCurrent();
} catch ( Throwable e ) {
tx.rollbackCurrent();
throw new ServletException( e );
}
}
Alternatively, you can use Seam or CDI or something like that.
Hope that helps!