Spring Data Access and Transaction Management

spring data access

Spring Data Access and Transaction Management

Now a days, almost each and every application need persistence of data which is a challenging task for developers. But Spring Data Access framework did the job and made it very easy for the developers. It provides a rich framework to access database. Spring data access framework heavily uses dependency injection mechanism which makes our code easy to maintain and test. It also takes the responsibility of exception handling where we don’t need to catch them explicitly. Using Template patterns provided by Spring data access framework, all the boilerplate code is hidden and now developers need to only concentrate solely on their business logic.  
spring data access
spring data access

Let’s first understand what is Transactions

We can say, A transaction is a logical unit of work that contains one or more SQL statements. A transaction is an atomic unit. When a transaction is performed then the effect of that transaction can be either all committed or all rolled back.

Spring Transaction Management

Spring Framework provides a consistent abstraction for transaction management. There are lots of benefits of using Transaction Management by spring framework as below
  1. Lightweight declarative syntax
  2. Transaction propagation
  3. Automatic rollback in case of some exception
  4. Simple API for programmatic transaction
  5. Exception handling

What are the advantages of Spring transaction support model

Previously, Java developers have had two choices for transaction management: global or local transactions but both of them have some limitations. Global Transactions
  • It enables you to work with multiple transactional resources like relational database and message queue.
  • Application server is required in order to manage global transactions through JTA.
  • You need to perfrom JNDI lookup in order to use JTA which normally only available on an application server environment.
  • Another preferred way to use global transactions via EJB CMT (Container management transactions).
  • CMT removed the need of JNDI lookups but EJB itself uses JNDI.
  • One downside of using CMT is that it is tied JTA and application server.
  • Global transaction management is useful in distributed environment.
Local Transactions
  • Local transaction is resource specific like transaction associated with JDBC connection.
  • They are easier to use.
  • They can not work with multiple transaction resouces like JTA transaction.
  • No application server involved in transaction management.
  • Local transactions are invansive to programming model.
  • Local transactions are mainly useful in centralized environment where resources are located at a single site.

Spring Transaction consistent programming Model

  • It resolved disadvantages of global and local transactions.
  • Enables application developers to use a consistent programming model for transaction management on any environment.
  • Developers can now write code once which can benefit from different transaction management in different environment.
  • It provides both declarative and programmatic transaction management.
  • Programmatic transaction management can run over any underlying transaction infrastructure.
  • With declarative model, developers need to write very less code related to transaction management, and hence it is not depend on Spring framework API or any other API.

Programmatic vs Declarative transaction management

Programmatic Transaction Management : In this transaction model, you have to maintain your transaction related stuff through programming. You will have to write code for transaction management which is flexible but not easy to maintain. Declarative Transaction Management : In this model, you don’t need to write code or very less to manage transactions. You can separate transaction management model from your business logic. It is not depend on any framework API and easy to maintain. Most of the developers prefer declarative transaction management over programmatic.

Spring Framework transaction abstraction

The key to the spring transaction abstraction strategy is defined by the org.springframework.transaction.PlatformTransactionManager interface.
public interface PlatformTransactionManager {

    TransactionStatus getTransaction(
            TransactionDefinition definition) throws TransactionException;

    void commit(TransactionStatus status) throws TransactionException;

    void rollback(TransactionStatus status) throws TransactionException;
}
Points to remember
  • This interface is a service provider (SPI).
  • PlatformTransactionManager is an interface so it can be easily mocked.
  • No JNDI lookup is required.
  • The TransactionException that can be thrown by any of PlatformTransactionManager inteface’s methods is unchecked.
Methods getTransaction(..) this method returns TransactionStatus object, depending on a TransactionDefinition parameter. The returned TransactionStatus object can be new transaction or existing transaction from the current call stack. commit(..) commits the given transaction. rollback(..) rolls back the given transaction in case of any exception.

TransactionDefinition interface

public interface TransactionDefinition {
   int getPropagationBehavior();
   int getIsolationLevel();
   String getName();
   int getTimeout();
   boolean isReadOnly();
}
Isolation the degree to which this transaction is isolated from work of other transactions. Propagation You can specify propagation behavior. Spring framework offers all of the transaction propagation options familiar from EJB CMT. Timeout How long transaction runs before timeout and being rolled back automatically. Read only status the status when read operation is performed but no data modification.

Transaction Status interface

The TransactionStatus interface provides a simple way for transactional code to control transaction execution and query transaction status.
public interface TransactionStatus extends SavepointManager {
    boolean isNewTransaction();
    boolean hasSavepoint();
    void setRollbackOnly();
    boolean isRollbackOnly();
    void flush();
    boolean isCompleted();
}

Implementing Data Source and Transaction Manager

You can implement data source and transaction manager in two ways, using XML configuration or Annotation based configuration. XML Based Configuration Data Source
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
    <property name="driverClassName" value="${jdbc.driverClassName}" />
    <property name="url" value="${jdbc.url}" />
    <property name="username" value="${jdbc.username}" />
    <property name="password" value="${jdbc.password}" />
</bean>
Txn manager
<bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
    <property name="dataSource" ref="dataSource"/>
</bean>
Annotation Based Configuration Data source
@Bean
	public DataSource dataSource() {
		DriverManagerDataSource driverManagerDataSource = new DriverManagerDataSource();
		driverManagerDataSource.setDriverClassName(environment.getRequiredProperty("jdbc.driverClassName"));
		driverManagerDataSource.setUrl(environment.getRequiredProperty("jdbc.url"));
		driverManagerDataSource.setUsername(environment.getRequiredProperty("jdbc.username"));
		driverManagerDataSource.setPassword(environment.getRequiredProperty("jdbc.password"));
		return driverManagerDataSource;
	}
Transaction Manager
@Bean
	@Autowired
	public HibernateTransactionManager transactionManager(SessionFactory s) {
	    HibernateTransactionManager txManager = new HibernateTransactionManager();
	    txManager.setSessionFactory(s);
	    return txManager;
	}
You can also see transaction manager and data access in action here CRUD operation using Spring, Hibernate and AngularJS.  

Leave a Reply

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