Java Reference
In-Depth Information
PlatformTransactionManager transactionManager) {
this.transactionManager = transactionManager;
}
public void purchase( final String isbn, final String username) {
TransactionTemplate transactionTemplate =
new TransactionTemplate(transactionManager);
transactionTemplate.execute(new TransactionCallbackWithoutResult() {
protected void doInTransactionWithoutResult(
TransactionStatus status) {
int price = getJdbcTemplate().queryForInt(
" SELECT PRICE FROM BOOK WHERE ISBN = ? " ,
new Object[] { isbn });
getJdbcTemplate().update(
" UPDATE BOOK_STOCK SET STOCK = STOCK - 1 " +
" WHERE ISBN = ? " , new Object[] { isbn });
getJdbcTemplate().update(
" UPDATE ACCOUNT SET BALANCE = BALANCE - ? " +
" WHERE USERNAME = ? " ,
new Object[] { price, username });
}
});
}
}
A TransactionTemplate can accept a transaction callback object that implements either the
TransactionCallback<T> or an instance of the one implementor of that interface provided by the
framework, the TransactionCallbackWithoutResult class. For the code block in the purchase()
method for deducting the book stock and account balance, there's no result to be returned, so
TransactionCallbackWithoutResult is fine. For any code blocks with return values, you should
implement the TransactionCallback<T> interface instead. The return value of the callback object
will finally be returned by the template's T execute() method. The main benefit is that the responsibility
of starting, rolling back, or commiting the transaction has been removed.
During the execution of the callback object, if it throws an unchecked exception (e.g.,
RuntimeException and DataAccessException fall into this category), or if you explicitly called
setRollbackOnly() on the TransactionStatus argument in the doInTransaction method, the
transaction will be rolled back. Otherwise, it will be committed after the callback object completes.
In the bean configuration file, the bookshop bean still requires a transaction manager to create a
TransactionTemplate .
<beans ...>
...
<bean id= " transactionManager "
class= " org.springframework.jdbc.datasource.DataSourceTransactionManager " >
<property name= " dataSource " ref= " dataSource " />
</bean>
Search WWH ::




Custom Search