Today i read about JTA api , i saw the class called UserTransactionManager. We have to start our transaction before we execute the SQL queries , so that if any exception happens we can rollback the changes.
Here my question is what exactly UserTransactionManager is doing? It is providing any stack .. to execute SQL query? How it is rollback the SQL query changes?
UserTransactionManager is an interface. Your container provides the implementation at runtime.
It uses a process called 2 phase commit where a “soft commit” happens and the rows are held in limbo, then a hard commit later. Here’s the basic overview:
The container communicates with the database when you open the transaction using the XA protocol and says “Hey give me a connection, but don’t actually write anything till disk (‘commit’) until I tell you so.”
Next, you run some queries, and flush them out to the database. When you flush your container asks the database, “Hey, run these queries, but don’t write anything until I tell you. If you can’t guarantee they’ll succeed throw and error immediately. If they will succeed, lock the rows and tables until you hear from me again and I give you the OK to commit”.
Finally, your program closes the UserTransaction. The container then says to the database, “Ok all those rows you have locked, flush everything to disk (commit) and unlock them.”
It’s actually more complicated then that, especially when you have coordinated global transactions… but basically if all the participants agree they can guarantee the commit, then they all commit, or nobody commits.
Further reading: