JTA Best Practices
Why is the JTA API your friend ? How does it help you writing better code ? Those are questions that we will try to answer here.
Why using the JTA API
Even if you're only planning to use a single database in your application (ie: if you don't plan to make use of 2 Phase Commit) using the JTA API is still a good idea as it helps separating concerns in your application.
The biggest benefit is the separation of the transaction management concern from the connection management concern. What does that mean ?
When using 'good old' JDBC, you work with a single object type: the Connection but this object is used twofolds: for data manipulation (ie: SELECT, INSERT, UPDATE, DELETE) and for transaction management (ie: COMMIT and ROLLBACK).
This is awkward as you often end up using an object for a concern (data manipulation) then keep it aside for later usage for another concern (committing or rolling back your changes).
Take this example:
This is unclean as to ensure all 3 business methods will execute in the same transaction, you have to pass them a Connection object which is not of any business value. It would be much better if the business methods could be left getting their resources themselves, like in this code:
This is much better as the calling code does not have to mess around with data access code: it is now completely hidden and can be encapsulated in some helper class or DAO. Unfortunately the data manipulation is not atomic anymore: if an error happen in executeBusinessLogicB then all modifications made by executeBusinessLogicA cannot be rolled back.
Object Oriented programming is about separation of concerns