2

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.

jabal
  • 11,987
  • 12
  • 51
  • 99

1 Answers1

1

You have to ensure that your class FooBarModelImpl is managed by the container in order to safely inject the PersistenceContext. See this answer regarding this point.

Once this is done, simply remove the begin() and commit() method invocations, because the transaction boundaries are automatically set by the container.

You'll have no more need to keep the reference to the UserTransaction object, either.

Community
  • 1
  • 1
perissf
  • 15,979
  • 14
  • 80
  • 117