Programmatic Transaction Management Example in Spring

This tutorial shows an example on programmatic transaction management in Spring. The declarative transaction management example uses two approaches – annotation based and XML based configurations. You can use as per your needs.

For introduction on Spring Transaction please go through Spring Transaction
Create a table in MySQL

 

Dump some data

 

Using PlatformTransactionManager

The DataSourceTransactionManager bean which we have declared in the applicationContext.xml files, is of type of PlatformTransactionManager. Hence we can directly use to handle programmatic transactions.

WEB-INF/applicationContext.xml

 

Following is a Dao class that uses PlatformTransactionManager. The code can be seen in addItem, updateItem and deleteItem method. So lets understand
Step 1 is to create an object of DefaultTransactionDefinition. This object exposes various setter methods to configure the transaction accordingly.
Step 2 is to to create the TransactionStatus object using the transaction definition we creataed in Step 1. Eventually this TransactionStatus will be used to commit or rollback the transaction like platformTransactionManager.commit(transactionStatus); or platformTransactionManager.rollback(transactionStatus);

 

Service class

 

Using Transaction Template

Spring TransactionTemplate is similar to JdbcTemplate and is used to abstract away the boilerplate code from the user. It provides simple callback methods which are automatically wrapped in a transaction. It also exposes direct setter methods for configuring various properties of transactions like setRollbackOnly etc. The Spring’s TransactionTemplate is initialized by providing a reference of DataSourceTransactionManager bean.

WEB-INF/applicationContext.xml

 

Using TransactionTemplate, we dont need to create a TransactionDefinition and Transaction object. The TransactionTemplate provides a callback method called execute where in we write our business logic that we want to wrap in a transaction. There are two types of callback methods that we can use to wrap our code i.e TransactionCallbackWithoutResult and TransactionCallback(T).

Change in ItemDaoImpl.java only and all other classes remain same.

 

Thanks for your reading please do not forget to leave a comment.

Soumitra

Software Professional, I am passionate to work on web/enterprise application. For more information please go to about me. You can follow on Twitter. You can be a friend on Facebook or Google Plus or Linkedin

Leave a Reply

Your email address will not be published. Required fields are marked *

Time limit is exhausted. Please reload CAPTCHA.