Thursday, December 27, 2007

Spring Transaction Management Example!

The service layer handles the business logic & DML actions on Entities.

The service methods are executed through Transaction proxies in order to manage the transaction.In other words,the Transaction Proxy wraps the execution of each transactional[which inserts/updates/deletes] service methods.


The Transaction Proxy is configured with TransactionInterceptor,TransactionManager and TransactionAttributes.

Transaction Attributes [REQUIRED,REQUIRED_NEW,SUPPORTS etc] tells us how the transaction to be handled.

The actual transaction[manage DB connection, execute actual JDBC, commit/rollback] is handled by Transaction Manager which is configured with Datasource.

The transaction proxy is in turn wrapped with Transaction Interceptor. This interceptor uses the Transaction Attributes and Transaction Manager to fulfill the transaction.

The Transaction Interceptor can be accompanied by one or more Pre and/or Post Interceptors.

The PreInterceptors wraps the TransactionInterceptor and therefore they are outside of transaction boundry.There can be one or more preInterceptors and they are executed in sequence as configured in chain.

The PostInterceptors are inside the TransactionInterceptor and they are executed one by one as configured in list.

After execution of all Post interceptors, the actual method implementation of the target object is execcuted.

Example Illustration:
The client[web layer] invokes service methods[which are transactional] as below.

//Find service bean through BeanFactory
IUserMaintService userService=ServiceFactory.getUserMaintService();
userService.insertUser(new User());

Here the service methods of IUserMaintService is configured on top of TransactionProxy [org.springframework.transaction.interceptor.TransactionProxyFactoryBean],
When a service method 'insertUser' is called, it executes the pre Interceptors if anything configured and then the transactionInterceptor.invoke method which in turn verifies the transaction attributes and create a transaction if required. This is the starting point of transaction boundary.After this, the sequence of post interceptors are getting executed and finally folowed by the 'TARGET implementation' method execution.


org.springframework.transaction.interceptor.TransactionProxyFactoryBean is configured with

-PreInterceptors org.springframework.transaction.interceptor.TransactionInterceptor --uses---->org.springframework.jdbc.datasource.DataSourceTransactionManager and org.springframework.transaction.interceptor.TransactionAttribute -PostInterceptors
-Actual Method Execution

No comments: