persistence@glassfish.java.net

Using EM within transactions

From: Uwe Gerger <Uwe.Gerger_at_gmx.de>
Date: Fri, 15 Sep 2006 12:08:54 +0200

Hi,
I have the following question about using an application managed "em" in web applications.

I have to call two methods of different objects in one servlet request. The two methods have to be part of one transaction.

Do I have to pass the em as a parameter to each method or can I use "em=emf.createEntityManager()" in each method?

For example:

doGet(...)
{
  A a = new A();
  B b = new B();

  
  utx.begin();

  em = emf.createEntityManager();

  a.saveA(em);

  b.saveB(em);

  utx.commit();
  
}

or can I use "em = emf.createEntityManager();" in each of the methods saveA and saveB so that the code snippet will look like this:

doGet()
{
 utx.begin();

  a.saveA();

  b.saveB();

  utx.commit();

}

In the methods:
saveA()
{
  em = emf.createEntityManager();
  ...
  em.persist(itemA);
  ...
}
 
saveB()
{
  em = emf.createEntityManager();
  ...
  em.persist(itemB);
  ...
}


Am I transaction save in both code snippets?

In Hibernate for example I have to use the same session within one transaction and within one thread, so I have to save the session in the threadlocal attribute...


Thanks in advance
Uwe
-- 
"Feel free" - 10 GB Mailbox, 100 FreeSMS/Monat ...
Jetzt GMX TopMail testen: http://www.gmx.net/de/go/topmail