I have a Java EE 6 servlet that creates an instance of FooBarModelImpl and this class uses JPA to fetch some resources.
public class FooBarModelImpl
{
@Resource
UserTransaction ut;
@PersistenceContext(unitName="fooBarUnit")
private EntityManager em;
public void addPackage(UpgradePackageEntity p)
{
try{
ut.begin();
em.persist(p);
ut.commit();
} catch (..) {}
}
}
The persistence unit is configured this way:
<persistence-unit name="fooBarUnit" transaction-type="JTA">
My question is how could I get rid of dealing with ut.begin() and ut.commit() manually? I’d like to use JPA so that the container deals with the transaction management.
You have to ensure that your class
FooBarModelImplis managed by the container in order to safely inject thePersistenceContext. See this answer regarding this point.Once this is done, simply remove the
begin()andcommit()method invocations, because the transaction boundaries are automatically set by the container.You’ll have no more need to keep the reference to the
UserTransactionobject, either.