Monday, January 9, 2012

How to use JBoss Transactions in Spring

JBoss transactions could used in a Spring application for various reasons. Here are some scenarios:

1. Your standalone Spring application uses multiple resources and you would like to make multiple phase transaction commits
2. Your are using Hibernate or some other DAO framework to access multiple databases in your Spring application and this application is being deployed in Tomcat or some other servlet/JSP container where you need a transaction manager
3. You just need a JTA transaction provider in Spring for some other framework or library such as JBoss's Infinispan

Step 1
Download JBossTM or add dependency to your maven project as follows.
.
.
<dependency>
  <groupId>org.jboss.jbossts</groupId>
  <artifactId>jbossjta</artifactId>
  <version>4.16.0.Final</version>
</dependency>
.
.

If this is a web application, you must remove servlet jar from the dependency as follows:
.
.
<dependency>
  <groupId>org.jboss.jbossts</groupId>
  <artifactId>jbossjta</artifactId>
  <version>4.16.0.Final</version>
   <exclusions>
     <exclusion>
       <artifactId>jboss-servlet-api_3.0_spec</artifactId>
       <groupId>org.jboss.spec.javax.servlet</groupId>
     </exclusion>
   </exclusions>
</dependency>
.
.

Step 2
JBossTM could be configured for timeout and transaction object store folders. These settings could be done via setting system variables in Java command.
.
.
java -Dcom.arjuna.ats.arjuna.coordinator.defaultTimeout=60 
-Dcom.arjuna.ats.arjuna.objectstore.objectStoreDir=/tmp/jbosstm/tx/a 
-DObjectStoreEnvironmentBean.objectStoreDir=/tmp/jbosstm/tx/a ...
.
.

Or through Spring's system properties in application context file.

.
.
<bean class="org.springframework.beans.factory.config.MethodInvokingFactoryBean" id="systemPrereqs">
  
  
  
  
    60
    /tmp/jbosstm/tx/a
    /tmp/jbosstm/tx/a 
       
  

</bean>
.
.

Step 3
Configure JBoss's Transaction Manager and User Transaction beans in Spring's application context as follows.
.
.
  
  
.

After this step, JBoss TM is up and running. If you like, you can use the transaction manager using the usual JNDI lookup.

Step 4
Finally, use JBossTM beans to configure Spring JTA transaction manager bean as follows.
.
.

  
    
  
  
    
  

.

This JTA transaction manager could now be used in your session factories or simply enable annotated driver transaction for auto injection.
.
.
<tx:annotation-driven></tx:annotation-driven>
.

Download Project
You can download my project from google code. SVN URL is http://ingenious-camel.googlecode.com/svn/trunk/SpringJBossTx