Java Reference
In-Depth Information
4-3. Managing Transactions Programmatically with the
Transaction Manager API
You need to precisely control when to commit and roll back transactions in your business methods, but
you don't want to deal with the underlying transaction API directly.
Spring's transaction manager provides a technology-independent API that allows you to start a new
transaction (or obtain the currently active transaction) by calling the getTransaction() method and
manage it by calling the commit() and rollback() methods. Because PlatformTransactionManager is
an abstract unit for transaction management, the methods you called for transaction management are
guaranteed to be technology independent.
How It Works
To demonstrate how to use the transaction manager API, let's create a new class, TransactionalJdbcBookShop ,
which will make use of the Spring JDBC template. Because it has to deal with a transaction manager, you add
a property of type PlatformTransactionManager and allow it to be injected via a setter method.
package com.apress.springenterpriserecipes.bookshop.spring;
import org.springframework.dao.DataAccessException;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
public class TransactionalJdbcBookShop extends JdbcDaoSupport implements
BookShop {
private PlatformTransactionManager transactionManager;
public void setTransactionManager(
PlatformTransactionManager transactionManager) {
this.transactionManager = transactionManager;
public void purchase(String isbn, String username) {
TransactionDefinition def = new DefaultTransactionDefinition();
TransactionStatus status = transactionManager.getTransaction(def);
try {
int price = getJdbcTemplate().queryForInt(
new Object[] { isbn });
Search WWH ::

Custom Search