Difference between UserTransaction and EntityTransaction
Asked Answered
P

1

22

Title says it all: What is the difference between a UserTransaction and an EntityTransaction?

My rudimentary understanding is that UserTransaction is used when JTA is required (e.g. to do queries on mulitple things), and that EntityTransaction is used when JPA only is required (e.g. when the query is atomic).

Is that the only difference between the two or is there more to it than that?

Pastelki answered 20/6, 2010 at 4:42 Comment(3)
possible duplicate of What is difference between @Resource UserTransaction and EntityManager.getTransaction()Gasholder
@Gasholder : That's a bit unfair, I'd only know that that question was a duplicate if I already knew the answer to the question in the first place! Neither the question nor the answer make any mention of EntityTransaction - I did search before asking.Pastelki
I completely understand that. That's also why I took the time to answer your question the best I could. It's just a common practice on SO to indicate possible duplicate so that people can read answers to both questions, it improves the quality of SO. It's not a critique or anything. The question is "closed as exact duplicate" only if there are 5 votes that mark it as such.Gasholder
G
28

My rudimentary understanding is that UserTransaction is used when JTA is required (e.g. to do queries on mulitple things), and that EntityTransaction is used when JPA only is required (e.g. when the query is atomic).

That's basically right, but your description of "multiple things" and "atomic" is a bit strange. JTA allows the developper to use distributed transaction to perform changes on multiples resources (database, JMS broker, etc.) atomically (all-or-nothing). If only one resource is accessed (e.g. one single database), you don't need JTA, but the transaction is still atomic (all-or-nothing). That's for instance the case when you use a regular JDBC transaction on one database.

Considering UserTransaction vs. EntityTransaction:

  • If JPA is use stand-alone, you use EntityTransaction to demarcate the transaction yourself.
  • If JPA is used within a managed environment where it integrates with JTA, you use UserTransaction. The EntityManager hooks itself into the JTA distributed transaction manager. The only subtlety I'm aware of considers the flush of the changes. When EntityTransaction is used, JPA know it needs to flush the changes. If transaction are controlled using UserTransaction, it needs to register a callback using JTA registerSynchronization, so that the changes are flushed to the database before the transaction completes. If you use EJB with CMT (container managed transaction), you don't even need to use UserTransaction: the app server starts and stops the transactions for you.

Related questions:

Gasholder answered 20/6, 2010 at 10:1 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.