I. Preface:
In the previous blog post, we used TransactionManager and threadlocal to complete thread-safe transaction management, and I wonder if anyone has discovered that the Accountservice code is riddled with many transaction-processing code. In fact, this code is repeated in many ways, and we can use template mode for optimization.
Two. Achieve:
1. Write a template class: Transactiontemplate
/** * Template class */public abstract class Transactiontemplate {public void Dojobintransaction () throws SQLException {try {//Open transaction T Ransactionmanager.begintransaction ();//Execute Business Method This.dojob ();//COMMIT Transaction Transactionmanager.commit ();} catch (Exception e) {//error, ROLLBACK TRANSACTION transactionmanager.rollback ();} finally {//close connection transactionmanager.close ();}} protected abstract void Dojob () throws Exception;}
Define a Dojobintransaction method in the Transactiontemplate class that starts the transaction first using TransactionManager in the method.
Then call the Dojob method to complete the business function, the Dojob method is an abstract method, the completion of the business function of the subclass should implement the method,
Finally, whether the commit transaction or the rollback transaction is successfully determined based on the Dojob method.
2. Transformation of Business Processing class Accountservice
/** * Business Logic Layer */public class Accountservice {public void Transfer (final account out, final account in, Final int. money) thro WS SQLException {new transactiontemplate () {@Overrideprotected void Dojob () throws Exception {//Query two accounts Accountdao account DAO = new Accountdao (); Account Outaccount = Accountdao.findaccountbyid (Out.getid ()); Account Inaccount = Accountdao.findaccountbyid (In.getid ());//Transfer-Modify the original Amount Outaccount.setmoney (Outaccount.getmoney ()- Inaccount.setmoney (Inaccount.getmoney () + money);//Update account Amount accountdao.update (Outaccount); Accountdao.update ( Inaccount);}}. Dojobintransaction ();}}
In Accountservice's transfer method, we created an anonymous Ttransactiontemplate class and implemented the Dojob method (two calls to DAO to complete the business operation in the Dojob method), Then call the Dojobintransaction method that calls Transactiontemplate.
Dojobintransaction internal help us call Dojob and implement transaction control
Java Transactions (iv)-Transforming transactions with template schemas