4-4. Managing Transactions Programmatically with a Transaction
Suppose that you have a code block, but not the entire body, of a business method that has the following
• Start a new transaction at the beginning of the block.
• Commit the transaction after the block completes successfully.
• Roll back the transaction if an exception is thrown in the block.
If you call Spring's transaction manager API directly, the transaction management code can be
generalized in a technology-independent manner. However, you may not want to repeat the boilerplate
code for each similar code block.
As with the JDBC template, Spring also provides a TransactionTemplate to help you control the overall
transaction management process and transaction exception handling. You just have to encapsulate
your code block in a callback class that implements the TransactionCallback<T> interface and pass it
to the TransactionTemplate 's execute method for execution. In this way, you don't need to repeat the
boilerplate transaction management code for this block. The template objects that Spring provides are
lightweight, and usually can be discarded or re-created with no performance impact. A JDBC template
can be re-created on-the-fly with a DataSource reference, for example, and so too can a
TransactionTemplate be re-created by providing a reference to a transaction manager. You can, of
course, simply create one in your Spring application context, too.
How It Works
A TransactionTemplate is created on a transaction manager just as a JDBC template is created on a data
source. A transaction template executes a transaction callback object that encapsulates a transactional
code block. You can implement the callback interface either as a separate class or as an inner class. If it's
implemented as an inner class, you have to make the method arguments final for it to access.
public class TransactionalJdbcBookShop extends JdbcDaoSupport implements
private PlatformTransactionManager transactionManager;
public void setTransactionManager(