I’ve recently been working on a task involving JPA persistence within a servlet running in JBoss 5. My servlet hasn’t been built using EJB, so at this stage I haven’t been using the JTA to manage my database transactions.
People more experienced than me assure me that it is good practice to use EJB, and use the JTA to manage transactions, as it will do a much better job than I ever could, so this will be a task for the near future.
However, in the meantime, I’m not using JTA. I’m using the Hibernate implementation of JPA provided within JBoss. The first thing you need to do to not use JTA is to set the transaction-type of the persistence-unit to RESOURCE_LOCAL. You then need to specify a non-jta-data-source within persistence.xml.
You define your data source within an xml file, and then add a module to the jboss-app.xml file within your servlet which references the data source file as a service.
I was using the H2 database. I found that I had to copy the h2*.jar file into JBOSS_HOME/server/default/lib in order for JBoss to find the jdbc driver classes.
To manage transactions, I found I had to follow the following workflow:
get entity manager from factory -> begin transaction -> do work -> commit -> close the entity manager.
And thats it. Hopefully further posts to follow regarding using EJB and JTA.