Effective Spring Transaction Management

Introduction:

Most of the time developers give little importance to transaction management. As a result, lots of code has to be reworked later or a developer implements transaction management without knowing how it actually works or what aspect needs to be used in their scenario.

An important aspect of transaction management is defining the right transaction boundary, when should a transaction start, when should it end, when data should be committed in DB and when it should be rolled back (in the case of exception).

The most important aspect for developers is to understand how to implement transaction management in an application, in the best way. So now let's explore different ways.

Ways of Managing Transactions

A transaction can be managed in the following ways:

1. Programmatically manage by writing custom code 

This is the legacy way of managing transaction.                      

EntityManagerFactory factory = Persistence.createEntityManagerFactory("PERSISTENCE_UNIT_NAME");                                       EntityManager entityManager = entityManagerFactory.createEntityManager();                   
Transaction transaction = entityManager.getTransaction()                  
try                                       
{  
   transaction.begin();                   
   someBusinessCode();                    
   transaction.commit();  
}                  
catch(Exception ex)                   
{                     
   transaction.rollback();  
   throw ex;                  
}

Pros:

Cons:

2. Use Spring to manage the transaction

Spring supports two types of transaction management:

  1.  Programmatic transaction management: This means that you have to manage the transaction with the help of programming. That gives you extreme flexibility, but it is difficult to maintain.
  2.  Declarative transaction management: This means you separate transaction management from the business code. You only use annotations or XML-based configuration to manage the transactions.
Declarative transactions are highly recommended. If you want to know the reason for this then read below else jump directly to Declarative transaction management section if you want to implement this option.

Now, let us discuss each approach in detail.

2.1 Programmatic transaction management:

The Spring Framework provides two means of programmatic transaction management.

a. Using the TransactionTemplate (Recommended by Spring Team):

Let's see how to implement this type with the help of below code (taken from Spring docs with some changes).

Please note that the code snippets are referred from Spring Docs.

Context XML file: 

<!-- Initialization for data source -->   
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">      <property name="driverClassName" value="com.mysql.jdbc.Driver"/>      
<property name="url" value="jdbc:mysql://localhost:3306/TEST"/>      
<property name="username" value="root"/>      
<property name="password" value="password"/>   
</bean>

<!-- Initialization for TransactionManager -->   
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">    
<property name="dataSource"  ref="dataSource" />  
</bean>

<!-- Definition for ServiceImpl bean -->   
<bean id="serviceImpl" class="com.service.ServiceImpl">    
<constructor-arg ref="transactionManager"/>   
</bean>


Service Class:

public class ServiceImpl implements Service
{        
  private final TransactionTemplate transactionTemplate;

  // use constructor-injection to supply the PlatformTransactionManager    
  public ServiceImpl(PlatformTransactionManager transactionManager)
  {     
this.transactionTemplate = new TransactionTemplate(transactionManager);   
  }

  // the transaction settings can be set here explicitly if so desired hence better control
  //This can also be done in xml file                  
  this.transactionTemplate.setIsolationLevel(TransactionDefinition.ISOLATION_READ_UNCOMMITTED);                   this.transactionTemplate.setTimeout(30); // 30 seconds       

  // and so forth...

  public Object someServiceMethod()
  {        
    return transactionTemplate.execute(new TransactionCallback() 
    {
     // the code in this method executes in a transactional context           
     public Object doInTransaction(TransactionStatus status)
     {                
     updateOperation1();     
        return resultOfUpdateOperation2();    
     }
   });   
}}


If there is no return value, use the convenient TransactionCallbackWithoutResult  class with an anonymous class as follows:

transactionTemplate.execute(new TransactionCallbackWithoutResult()
{    
protected void doInTransactionWithoutResult(TransactionStatus status)
{       
  updateOperation1();      
   updateOperation2();  
} 
});

b. Using a PlatformTransactionManager implementation directly:

Let's see this option again with the help of code.

<!-- Initialization for data source -->  
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">    
<property name="driverClassName" value="com.mysql.jdbc.Driver"/>     
<property name="url" value="jdbc:mysql://localhost:3306/TEST"/>      
<property name="username" value="root"/>      
<property name="password" value="password"/>  
</bean>

<!-- Initialization for TransactionManager -->   
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">      
<property name="dataSource"  ref="dataSource" />       
</bean>
public class ServiceImpl implements Service
{    
 private PlatformTransactionManager transactionManager;

 public void setTransactionManager( PlatformTransactionManager transactionManager)
 {    
   this.transactionManager = transactionManager;  
 }

DefaultTransactionDefinition def = new DefaultTransactionDefinition();

// explicitly setting the transaction name is something that can only be done programmatically
def.setName("SomeTxName");
def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);

TransactionStatus status = txManager.getTransaction(def);

try 
{    
// execute your business logic here
}
catch (Exception ex)
{    
txManager.rollback(status);   
throw ex;
}

txManager.commit(status);

}

Now, before going to the next way of managing transactions, lets see how to choose which type of transaction management to go for.

Choosing between Programmatic and Declarative Transaction Management:

2.2. Declarative Transaction (Usually used almost in all scenarios of any web application)

Step 1: Define a transaction manager in your Spring application context XML file.

<bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"/>
<tx:annotation-driven transaction-manager="txManager"/>          

Step 2: Turn on support for transaction annotations by adding below entry to your Spring application context XML file.

OR add @EnableTransactionManagement   to your configuration class as below:

@Configuration
@EnableTransactionManagement
public class AppConfig
{
 ...
}
Spring recommends that you only annotate concrete classes (and methods of concrete classes) with @Transactional annotation as compared to annotating interfaces.

The reason for this is if you put an annotation on the Interface Level and if you are using class-based proxies ( proxy-target-class="true" ) or the weaving-based aspect ( mode="aspectj" ), then the transaction settings are not recognized by the proxying and weaving infrastructure .i.e Transactional behavior will not be applied.

Step 3: Add the @Transactional annotation to the Class (or method in a class) or Interface (or method in an interface).

<tx:annotation-driven proxy-target-class="true">

Default configuration: proxy-target-class="false"  

Let us now understand different @Transactional   attributes.

@Transactional (isolation=Isolation.READ_COMMITTED)

DEFAULT: Use the default isolation level of the underlying database.

READ_COMMITTED: A constant indicating that dirty reads are prevented; non-repeatable reads and phantom reads can occur.

READ_UNCOMMITTED: This isolation level states that a transaction may read data that is still uncommitted by other transactions.

REPEATABLE_READ: A constant indicating that dirty reads and non-repeatable reads are prevented; phantom reads can occur.

SERIALIZABLE: A constant indicating that dirty reads, non-repeatable reads, and phantom reads are prevented.

What do these Jargons dirty reads, phantom reads, or repeatable reads mean?

@Transactional(timeout=60)

Defaults to the default timeout of the underlying transaction system.

Informs the tx manager about the time duration to wait for an idle tx before a decision is taken to rollback non-responsive transactions.

@Transactional(propagation=Propagation.REQUIRED)

If not specified, the default propagational behavior is REQUIRED. 

Other options are  REQUIRES_NEW , MANDATORY  , SUPPORTS  , NOT_SUPPORTED  , NEVER  , and  NESTED .

REQUIRED

REQUIRES_NEW

MANDATORY

SUPPORTS

NOT_SUPPORTED

NEVER

@Transactional (rollbackFor=Exception.class)

@Transactional (noRollbackFor=IllegalStateException.class)

Now the last but most important step in transaction management is the placement of @Transactional annotation. Most of the times, there is a confusion where should the annotation be placed: at Service layer or DAO layer?

@Transactional: Service or DAO Layer?

The Service is the best place for putting @Transactional, service layer should hold the detail-level use case behavior for a user interaction that would logically go in a transaction.

There are a lot of CRUD applications that don't have any significant business logic for them having a service layer that just passes data through between the controllers and data access objects is not useful. In these cases we can put transaction annotation on Dao.

So in practice, you can put them in either place, it's up to you.

Also if you put @Transactional   in DAO layer and if your DAO layer is getting reused by different services then it will be difficult to put it on DAO layer as different services may have different requirements.

If your service layer is retrieving objects using Hibernate and let's say you have lazy initializations in your domain object definition then you need to have a transaction open in service layer else you will face LazyInitializationException  thrown by the ORM.

Consider another example where your Service layer may call two different DAO methods to perform DB operations. If your first DAO operation failed, then the other two may be still passed and you will end up inconsistent DB state. Annotating a Service layer can save you from such situations.

Hope this article helped you.

 

 

 

 

Top