Spring Book – Chapter 9 – Transaction Management

Programmatic Transaction Management

As the name implies, this style allows you to manage transactions in your source code programmatically. That’s means, with this style; you specifically enclose transactional logic using method calls into the Spring API. This style extremely flexible but can be very difficult to maintain. There are two means of doing transactions in Spring programmatically. They are:

  • PlatformTransactionManager
  • TransactionTemplate

PlatformTransactionManager

The org.springframework.transaction.PlatformTransactionManager interface is the key abstraction in the Spring API providing essential methods for controlling transaction operations at run-time: begin, commit and rollback.

The org.springframework.transaction .PlatformTransactionManager (Listing 9-3) interface uses org.springframework.transaction.TransactionDefinition (Listing 9-4) and org.springframework.transaction.TransactionStatus (Listing 9-5) to create and manage transactions. This is called as a Service Provider Interface (SPI) which can also be mocked and stubbed to provide programmatic transaction management in your application. Any implementation of this interface contains the salient details of the underling transaction manager which it interacts to perform transaction management. For example, the org.springframework.jdbc.datasource.DataSourceTransactionManager class manages transactions performed within a JDBC DataSource, org.springframework.orm.jdo.JdoTransactionManager class controls transactions performed in a JDO session, org.springframework.orm.hibernate4.HibernateTransactionManager class does the same in a Hibernate session, and org.springframework.orm.jpa.JpaTransactionManager class supports transaction for JPA. Figure 9-3 below shows the hierarchy of classes and its implementation technologies.

Figure 9-3. PlatformTransactionManager interface, its implementations and corresponding transaction technologies

Out-of-box local and global Transaction Manager implementation provided by Spring can be summarized as shown in Table 9-1 below.

Local

Transaction

Managers

Implementation Class

Details

DataSourceTransactionManager Entrusted with managing a single JDBC datasource resource.
JpaTransactionManager Capable of managing a single JPA resource.
JmsTransactionManager Capable of handling single JMS resource.
HibernateTransactionManager Capable of handling single Hibernate resource.
JdoTransactionManager Capable of handling single JDO resource.
CciLocalTransactionManager Capable of handling single Java Connection Architecture (JCA) resource.

Global

Transaction

Managers

JtaTransactionManager Capable of handling more than one resource in a transaction and is also capable of supporting XA transaction API. To use this transaction manager you will have to deploy your application inside a JEE server.
WeblogicJtaTransactionManager BEA Weblogic container specific implementation of JtaTransactionManager.
WebsphereUowTransactionManager IBM Websphere container specific implementation of JtaTransactionManager.
OC4JJtaTransactionManager Oracle OC4J container specific implementation of JtaTransactionManager.

Table 9-1. Local and Global Transaction Manager implementation Classes by Spring

Note: A transaction manager is the part of an application that is responsible for coordinating transactions across one or more resources. It works with applications and application servers to provide services to control the scope and duration of transactions. It also helps coordinate the completion of global transactions across multiple transactional resource managers.

Listing 9-3. PlatformTransactionManager interface definition

[java]package org.springframework.transaction;

public interface PlatformTransactionManager {

TransactionStatus getTransaction(TransactionDefinition definition)

throws TransactionException;

void commit(TransactionStatus status) throws TransactionException;

void rollback(TransactionStatus status) throws TransactionException;

}[/java]

Applications can use this interface directly, but it is not primarily meant as an API. Spring out-of-box has provided implementations for various transaction technologies (Figure 9-3 only shows some of the common ones). If you would like to have your own implementation, it is recommended to derive from Spring provided abstract class namely, org.springframework.transaction.support.AbstractPlatformTransactionManager, which pre-implements the defined transaction propagation behavior and takes care of transaction synchronization handling as well in all aspects.

Listing 9-4. TransactionDefinition interface definition

[java]package org.springframework.transaction;

public interface TransactionDefinition {

//Propagation and isolation constants

int getPropagationBehavior();

int getIsolationLevel();

int getTimeout();

boolean isReadOnly();

String getName();

}[/java]

The basic transactional unit of work in a Spring transaction is exposed through the org.springframework.transaction.TransactionDefinition interface, which controls basic properties of a transaction. TransactionDefinition interface defines Spring-compliant transaction properties. It has constants for both transaction propagation and isolation levels. It has constants analogous to EJB transaction attributes. It is also used to specify the characteristics of a newly created transaction.

Listing 9-5. TransactionStatus interface definition

[java]package org.springframework.transaction;

public interface TransactionStatus extends SavepointManager {

boolean isNewTransaction();

boolean hasSavepoint();

void setRollbackOnly();

boolean isRollbackOnly();

void flush();

boolean isCompleted();

}[/java]

To provide fine-grained transaction monitoring in your application, Spring provides the org.springframework.transaction.TransactionStatus interface which allows your application to check the status of the running transaction. This simple interface exposes the setRollbackOnly method, which causes the current transaction to rollback and end as opposed to having a transaction abnormally terminate because of an exception. The propagation behavior is similar to the org.springframework.transaction.TransactionDefinition interface. You can programmatically retrieve the status of a transaction and decide as to what can be done on it. This interface derives from org.springframework.transaction.SavepointManager interface to provide access to savepoint management facilities, if the underlying transaction managers support savepoint management.

Note: A transaction context contains information about a transaction. Theoretically, a transaction context is a data structure that contains a unique transaction identifier, a timeout value, and the reference to the transaction manager that controls the transaction scope of your application.

A transaction manager associates a transaction context with the currently executing thread. Multiple threads may be associated with the same transaction context, dividing a transaction’s work into parallel tasks. If a transaction spans across multiple transaction managers, the transaction context has to be passed throughout.

TransactionTemplate

The class org.springframework.transaction.support.TransactionTemplate, like any other template class in the Spring Framework, this class also follows the template pattern. This is the template class that simplifies programmatic transaction demarcation and transaction exception handling. The central method is execute(org.springframework.transaction.support.TransactionCallback), supporting transactional code that implements the TransactionCallback interface. It frees developer from boilerplate code like acquisition and release of transaction resources from the application code. It is the developers responsibility to implement the TransactionCallback interface and the code inside the method doInTransaction(TransactionStatus status) in this interface executes in the context of a transaction. This is shown in the Listing 9-6 below.

Listing 9-6. Usage of TransactionTemplate in which a set of code is executed and there is a result after execution

[java]@Service

public class LoyaltyService {

private final TransactionTemplate transactionTemplate;

public SimpleService(PlatformTransactionManager transactionManager) {

this.transactionTemplate = new TransactionTemplate(transactionManager);

}

public Object calculateLoyaltyPoints() {

return transactionTemplate.execute(new TransactionCallback() {

public Object doInTransaction(TransactionStatus status) {

//Do anything.. Everything is in a transaction context

return “Return any object”;

}

});

}

}[/java]

Listing 9-7. Usage of TransactionTemplate in which a set of code is executed and there is not result after execution

[java]@Service

public class LoyaltyService {

private final TransactionTemplate transactionTemplate;

public SimpleService(PlatformTransactionManager transactionManager) {

this.transactionTemplate = new TransactionTemplate(transactionManager);

}

public Object doSomeOperation() {

return transactionTemplate.execute(new TransactionCallbackWithoutResult() {

public Object doInTransactionWithoutResult(TransactionStatus

status) {

//Do anything.. Everything is in a transaction context.. you

cannot return anything

}

});

}

}[/java]

Listing 9-8. Setting various properties in TransactionTemplate

[java]@Service

public class LoyaltyService {

private final TransactionTemplate transactionTemplate;

public SimpleService(PlatformTransactionManager transactionManager) {

this.transactionTemplate = new TransactionTemplate(transactionManager);

//Setting of transaction isolation levels

this. transactionTemplate.setIsolationLevel

(TransactionDefinition.ISOLATION_READ_COMMITTED);

//Setting transactio timeout.. setting it to 50 seconds

this. transactionTemplate.setIsolationLevel(50);

}

//….

}[/java]

Page Visitors: 9636

The following two tabs change content below.
Tomcy John

Tomcy John

Blogger & Author at javacodebook
He is an Enterprise Java Specialist holding a degree in Engineering (B-Tech) with over 10 years of experience in several industries. He's currently working as Principal Architect at Emirates Group IT since 2005. Prior to this he has worked with Oracle Corporation and Ernst & Young. His main specialization is on various web technologies and acts as chief mentor and Architect to facilitate incorporating Spring as Corporate Standard in the organization.
Tomcy John

Latest posts by Tomcy John (see all)

1 thought on “Spring Book – Chapter 9 – Transaction Management

Leave a Reply

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