A Brief Concept Of Spring Transaction Management

Posted By : Kiran Sharma | 31-May-2018

In this blog, we will learn how @Transactional works in spring framework. This is the most recommended way to handle transactions in spring. Spring supports two types of transactions - programmatic and declarative transactions.

 

Programmatic transactions - Using this, we need to write explicit code for transaction management so as to commit on successful completion and roll back in case of failure and the transaction management code is tightly bound to the business logic.

 

Declarative transactions -Using this transaction management code is loosely coupled from business logic. To implement this spring provides @Transactional Implementation of @Transactional. The Declarative approach saves us from writing the hard code in our source code withthe help of configuration which means we can separate transaction management code from the business code. We have two ways to use this declarative transactions - 1)XML based 2)Annotation based. 

XML Based

1.We have to first empower explanations in our Spring application by including the required design into spring setting document

<tx:annotation-driven transaction-manager="transMang"/>
 

2. Define a transaction manager bean with the same name as of transaction manager.

<bean id="transMang" class="org.springframework.orm.jpa.JpaTransactionManager">
	<property name="entityManagerFactory" ref="entityManagerFactory" />
</bean>
 

 

Annotation Based

Now we can use @Transactional annotation at class or method level. When a class declares @Transactional on itself spring wraps the bean in the proxy without telling bean.

Calling a method on transaction proxy looks like 

 

The proxy object is supplied with a TransactionInterceptor. This interceptor is created by spring. The method with @Transactional annotation is called from client code, the TransactionInterceptor is invoked very first from the proxy object. This begins the transaction and invokes the method on the target bean. At last TransactionInterceptor commits/rollback the transaction.

By default, @Transactional sets the propagation to REQUIRED, the readOnly flag is set to false.

Transaction Logging Issues related to the transaction can be better understood by logging.

 

About Author

Author Image
Kiran Sharma

Kiran has good knowledge of java with Servlets, JSPs, Spring, and hibernate frameworks. She is very honest towards her work. Her hobby is listening to music.

Request for Proposal

Name is required

Comment is required

Sending message..