How to use Bean Managed Transactions with EJB3, JPA and JTA
During a “little” project I am doing in my spare time, I found out that switching to Bean Managed Transactions (BMT) wasn’t as easy as I expected. When you’ve used Container Managed Transactions (CMT) and are switching to BMT with JTA like I was, you need to know the following:
First of all the persistence unit needs to define a <jta-data-source> and not a <non-jta-data-source>
Because you are using JTA you can’t fetch a new EntityTransaction from the entity manager. You’ll have to get a UserTransaction from the EJBContext. To do this, have the EJB container inject the EJBContext using the following code:
private EJBContext context;
After the container has injected the EJBContext you can simply start, use and commit a transaction like this:
UserTransaction tx = context.getUserTransaction();
Knowing the above, using BMT with EJB3, JTA and JPA is really easy! The point is to find the right information. And now you have!