Java Reference
In-Depth Information
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 });
transactionManager.commit(status);
} catch (DataAccessException e) {
transactionManager.rollback(status);
throw e;
}
}
}
Before you start a new transaction, you have to specify the transaction attributes in a transaction
definition object of type TransactionDefinition . For this example, you can simply create an instance of
DefaultTransactionDefinition to use the default transaction attributes.
Once you have a transaction definition, you can ask the transaction manager to start a new
transaction with that definition by calling the getTransaction() method. Then it will return a
TransactionStatus object to keep track of the transaction status. If all the statements execute
successfully, you ask the transaction manager to commit this transaction by passing in the
transaction status. Because all exceptions thrown by the Spring JDBC template are subclasses of
DataAccessException , you ask the transaction manager to roll back the transaction when this kind
of exception is caught.
In this class, you have declared the transaction manager property of the general type
PlatformTransactionManager . Now you have to inject an appropriate transaction manager
implementation. Because you are dealing with only a single data source and accessing it with
JDBC, you should choose DataSourceTransactionManager . Here you also wire a dataSource because
the class is a subclass of Spring's JdbcDaoSupport , which requires it.
<beans ...>
...
<bean id= " transactionManager "
class= " org.springframework.jdbc.datasource.DataSourceTransactionManager " >
<property name= " dataSource " ref= " dataSource " />
</bean>
<bean id= " bookShop "
class= " com.apress.springenterpriserecipes.bookshop.spring.
TransactionalJdbcBookShop " >
<property name= " dataSource " ref= " dataSource " />
<property name= " transactionManager " ref= " transactionManager " />
</bean>
</beans>
Search WWH ::




Custom Search