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 simple example to illustrate our concern:
This code is reasonably clean as the calling business method (
executeA_B_C()) does no know that the underlying logic is using JDBC which is good Object Oriented design. It is also possible to encapsulate the JDBC boilerplate code in some helper class, DAO or even delegate that to a more powerful solution like Spring's JdbcTemplate. Data access code will change in that case but the idea stays the same.
Unfortunately the data manipulation is not atomic: if an error happen in
executeBusinessLogicB then all modifications made by
executeBusinessLogicA cannot be rolled back.
A commonly found way to fix this problem is by sharing the
Connection object between all 3 business methods:
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: