users@glassfish.java.net

Re: EE5 JPA with JTA/UserTransaction -- non-Container managed transactions

From: Sahoo <sanjeeb.sahoo_at_oracle.com>
Date: Mon, 13 Dec 2010 08:22:33 +0530

Persistence.createEMF()
  is not same as
@PersistenceUnit
EMF emf;

If you don't like injection, you can look up emf using JNDI and that
will give you same behavior, but Persistence.creatEMF is called "Java
SE" style of obtaining an EMF and that's not recommended to be used in
EE apps, for in Java SE, things like JTA may not be supported by the
EMF. In fact, unless you explicitly configure transaction-type in your
persistence.xml, the default value is RESOURCE_LOCAL for Java SE and JTA
for Java EE.

I am quite sure the spec says all these things.

Sahoo
On Monday 13 December 2010 06:31 AM, emiddio-frontier wrote:
> Why does code like:
> emf =
> javax.persistence.Persistence.createEntityManagerFactory("EmployeeService");
>
> provide an emf that will not work properly?
>
> see more info below:
>
> Rather than code like:
>
> @PersistenceUnit(unitName = "EmployeeService")
> public EntityManagerFactory emf;
> @Resource
> public UserTransaction utx;
>
> the JavaEE API says one can do the following:
>
> public EntityManagerFactory emf;
> public UserTransaction utx;
>
> and initialize emf and utx like:
>
> InitialContext ic = new InitialContext();
> utx = (UserTransaction) ic.lookup("java:comp/UserTransaction");
> emf =
> javax.persistence.Persistence.createEntityManagerFactory("EmployeeService");
>
> -----------------------------------------------------------------------
>
> Within a Servlet with JTA/JPA, code like the shown below works as long
> as emf
> is only obtained with/via the @PersistenceUnit annotation;
>
> EntityManager em = emf.createEntityManager();
> utx.begin();
> em.joinTransaction();
> Employee emp = em.find(Employee.class, id);
> utx.commit();
>
> the above code works if utx is obtained as a
> @Resource
> public UserTransaction utx;
>
> or as
>
> utx = (UserTransaction) ic.lookup("java:comp/UserTransaction");
>
>
> the code fails if emf is obtained as
> emf =
> javax.persistence.Persistence.createEntityManagerFactory("EmployeeService");
>
>
> as opposed to
> @PersistenceUnit(unitName = "EmployeeService")
> public EntityManagerFactory emf;
>
> the Java EE5/6 API say it should work.
>
> thanks
>
> gary
>