JPA - Is there a way to create something like a nested transaction?

2,665 views
Skip to first unread message

laguiz

unread,
Mar 14, 2011, 6:39:38 PM3/14/11
to play-framework
Is there a way to create a nested JPA transaction?

By using "JPAPlugin.closeTx" and "JPAPlugin.startTx", we should comit
current transaction before start a new one and start a new one for the
rest of the http request. I don't like it because I need my business
transaction bound to the currect http call.

I would like to create a nested transaction (pause the first one,
perform my local transaction, resume the first one). Or maybe create
new transaction next the the existing one?

I tried something like that :

EntityManager em = JPA.newEntityManager();
try {
em.getTransaction().begin();
myObjectToSave.save();
em.getTransaction().commit();
} catch (Exception e) {
if (em.getTransaction().isActive()) {
em.getTransaction().rollback();
}
} finally {
if (em.isOpen()) {
em.close();
}
}

But if I get later an exception after the commit, transaction is
rollbacked :/
I even tried with autocommit but transaction is rollbacked too.

(I see in the playframework code that the transaction is bound to the
current thread using ThreadLocal.)

Is there a way to do this (nested transaction or second independent
transaction)?

Thank you,
Max

Guillaume Bort

unread,
Mar 15, 2011, 7:34:23 AM3/15/11
to play-fr...@googlegroups.com
JPA doesn't support nested transaction.

Also if create a new EntityManager with its own transaction, you need
to use it explicitly, because default Model operations like save(),
find(), etc. will always use the Play managed EntityManager.

> --
> You received this message because you are subscribed to the Google Groups "play-framework" group.
> To post to this group, send email to play-fr...@googlegroups.com.
> To unsubscribe from this group, send email to play-framewor...@googlegroups.com.
> For more options, visit this group at http://groups.google.com/group/play-framework?hl=en.
>
>

--
Guillaume Bort, http://guillaume.bort.fr

For anything work-related, use g...@zenexity.fr; for everything else,
write guillau...@gmail.com

laguiz

unread,
Mar 15, 2011, 2:12:50 PM3/15/11
to play-framework
It works if I use the EntityManager directly to persist :

EntityManager em = JPA.newEntityManager();
try {
em.getTransaction().begin();
//myObjectToSave.save();
em.persist(myObjectToSave); // ok use new
transaction!
em.getTransaction().commit();
} catch (Exception e) {
if (em.getTransaction().isActive()) {
em.getTransaction().rollback();
}
} finally {
if (em.isOpen()) {
em.close();
}
}


Thank you Guillaume :)
> Guillaume Bort,http://guillaume.bort.fr
>
> For anything work-related, use g...@zenexity.fr; for everything else,
> write guillaume.b...@gmail.com
Reply all
Reply to author
Forward
0 new messages