In every source I've seen, a transaction is defined as a set of operations that succeed or fail together. However, using an EntityManager
in JPA, it seems to require a transaction even to persist a single entity that I have created in memory. What is the meaning of transaction? Isn't this operation already atomic? How could I rollback a single entity.persist()
? Is there a clear definition of the concept anywhere in the java EE documentation?

- 27,712
- 9
- 72
- 90
-
1There's tons of reading on this, really. https://en.wikibooks.org/wiki/Java_Persistence/Transactions – lexicore Jan 11 '17 at 20:14
-
1thanks. problem is, I've read a ton, but still, even the link defines transaction as "a set of operations". why should do I *have to* use it for a single entity.persist? – blue_note Jan 11 '17 at 20:18
-
Who says you have to? – lexicore Jan 11 '17 at 20:40
-
Java, unfortunately: for a single "em.persist(myentity);" I get "TransactionRequiredException: no transaction is in progress" – blue_note Jan 11 '17 at 20:56
-
1See [here](http://stackoverflow.com/questions/21672454/application-managed-jpa-when-is-transaction-needed/21673304#21673304) – Andrew S Jan 11 '17 at 21:46
2 Answers
Thinking that EntityManager.persist()
is atomic is like always using SQL with auto-commit enabled. A transaction is used to create an atomic operation which allows you to insert one or more rows into one or more tables as a single atomic operation, either evertyhing is inserted or nothing is inserted.
If you didn't have transaction, and you insert a User and his two phone numbers (two tables), and something goes wrong when you insert the second phone number, you want the entire transaction to fail, rather than have inconsistent data.
If you use an application managed EntityManager, you control the transaction progammaticrally (EntityManager.getTransaction()
), so you control which operations (inserts/updates) should happen as an atomic operation.
If you use a container managed EntityManager (Spring, JavaEE) then the transaction is declarative (@Transactional annotation), so transactions are basically method scoped (typically propagated through multiple method calls).
This is just the tip of the iceberg when it comes to transactions, there are other things like Isolation levels, and serialised transaction, but lets talks about that another time :)

- 4,820
- 2
- 15
- 30
Isn't this operation already atomic? How could I rollback a single
entity.persist()
?
It might or might not be atomic. For instance, if your entity has a relationship to another entity with CascadeType.PERSIST
, or uses a secondary table, it will require more than one SQL statement to make it persistent.
There really isn't a one-to-one mapping between EntityManager
calls and SQL statements, neither are the two required to coincide in time.

- 9,978
- 2
- 28
- 47