Spring's support for JTA

Source: Internet
Author: User

Introduction:
Spring's AOP technology allows us to enjoy a sumptuous feast of declarative transactions without EJB.
By working with ObjectWeb's JOTM Open source project, spring can also provide JTA transactions without the need for a Java EE application server.

Sping three ways to support JTA:
1. Direct integration JOTM provides JTA transaction management (no application server support, often for unit testing)
2. Indirect implementation of JTA transaction management by referencing Jndi data sources for application servers (such as Tomcat)
3. Using the application server-specific transaction manager, use the advanced features of the JTA transaction (Weblogic,websphere)

1. JOTM Direct Integration
1.1. Add the following class library Jotm to the classpath:
Jotm.jar
Xapool.jar
Jotm_jrmp_stubs.jar
Jta-spec1_0_1.jar
Connector-1_5.jar

1.2. Write the JOTM configuration file and put it under the Classpath
Carol.properties
#JNDI调用协议
Carol.protocols=jrmp
#不使用CAROL Jndi Wrapper
Carol.start.jndi=false
#不启动命名服务器
Carol.start.ns=false

1.3. Build two databases on MySQL
Run SQL scripts in the MySQL database, build topicdb and postdb two databases,
Create a t_topic table in the TOPICDB database and create a t_post table in the POSTDB database.
We want to do JTA transactions on these two databases.

1.4. Configure JOTM in the spring configuration file and implement the specific business class
Code Listing 1 Applicationcontext-jta.xml

<bean id= "Jotm" class= "Org.springframework.transaction.jta.JotmFactoryBean"/>①jotm local instance ②JTA transaction manager <bean id= "Txmanager" class= "Org.springframework.transaction.jta.JtaTransactionManager" > <property name= " UserTransaction "ref=" Jotm "/>②-1: Specifies the UserTransaction property </bean>③xapool configuration, which contains an XA data source corresponding to the TOPICDB database <bean Id= "Topicds" class= "Org.enhydra.jdbc.pool.StandardXAPoolDataSource" destroy-method= "Shutdown" > <property            Name= "DataSource" >③-1: Internal xa data source <bean class= "Org.enhydra.jdbc.standard.StandardXADataSource" destroy-method= "Shutdown" > <property name= "TransactionManager" ref= "Jotm"/> <property Name= "drivername" value= "com. MySQL.jdbc.Driver "/> <property name=" url "value=" jdbc:mysql://localhost:3309/topicdb "/> </ bean> </property> <property name= "user" value= "root"/> <property name= "password" value= "1234" /></bean>④ in a similar way as ③Configure another xapool, corresponding to the POSTDB database, <bean id= "Postds" class= "Org.enhydra.jdbc.pool.StandardXAPoolDataSource" destroy-method= "Shutdown" > <property name= "DataSource" > <bean class= "Org.enhydra.jdbc.standard.Stand Ardxadatasource "destroy-method=" shutdown "> <property name=" TransactionManager "ref=" Jotm "/&G            T <property name= "drivername" value= "Com.mysql.jdbc.Driver"/> <property name= "url" value= "jdbc:mysql:// Localhost:3309/postdb "/> </bean> </property> <property name=" user "value=" root "/> & Lt;property name= "password" value= "1234"/></bean>⑤ Configure the Spring JDBC template to access the TOPICDB data source <bean id= "Topictemplate" class= "Org.springframework.jdbc.core.JdbcTemplate" > <property name= "dataSource" ref= "Topicds"/></bean    >⑥ Configuring the Spring JDBC template to access the POSTDB data source <bean id= "posttemplate" class= "Org.springframework.jdbc.core.JdbcTemplate" > <property name= "DataSource" ref= "Postds"/></bean>⑦ topicdao<bean id= "Topicdao" class= "Com.baobaotao.dao.jdbc.TopicJdbcDao" based on topictemplate data source > <property name= "jdbctemplate" ref= "topictemplate"/></bean>⑧ posttemplate Postdao<bean based on id= data source " Postdao "class=" Com.baobaotao.dao.jdbc.PostJdbcDao "> <property name=" jdbctemplate "ref=" Posttemplate "/> </bean>⑨ Business class for cross-database JTA transactions <bean id= "Bbtforum" class= "Com.baobaotao.service.impl.BbtForumImpl" > < Property Name= "Topicdao" ref= "Topicdao"/> <property name= "Postdao" ref= "Postdao"/></bean> ⑩ driving @transaction annotations in Bbtforumimpl business class <tx:annotation-driven transaction-manager= "Txmanager"/>

Code Listing 2 Bbtforumimpl

Package Com.baobaotao.service.impl;  Import org.springframework.transaction.annotation.Transactional;  Import Com.baobaotao.dao.PostDao;  Import Com.baobaotao.dao.TopicDao;  Import Com.baobaotao.domain.Forum;  Import Com.baobaotao.domain.Topic;  Import Com.baobaotao.service.BbtForum;  @Transactional//① transaction annotations so that spring dynamically weaves transaction management functions Public  class Bbtforumimpl implements Bbtforum {    private Topicdao Topicdao;      Private Postdao Postdao;     public void Addtopic (Topic Topic) throws Exception {     //② the method will be applied JTA the enhanced topicdao.addtopic of the transaction      (Topic);      Postdao.addpost (Topic.getpost ());}      }

1.5. Run the test in spring

Package com.baobaotao.service;  Import org.springframework.test.AbstractDependencyInjectionSpringContextTests;  ..... public class Testbbtforumjta extends abstractdependencyinjectionspringcontexttests{    private bbtforum bbtforum;      Private final Logger Logger = Logger.getlogger (GetClass ());          public void Setbbtforum (Bbtforum bbtforum) {          this.bbtforum = bbtforum;      }          Protected string[] Getconfiglocations () {        return new string[]{"Classpath:applicationcontext-jta.xml"};      }          public void Testaddpost () throws exception{          logger.info ("Begin ...");          Topic Topic = new Topic ();          Topic.settopictitle ("TITLE-PFB");                  Post post = new post ();          Post.setposttext ("Post CONTENT-PFB");          Topic.setpost (post);                  Bbtforum.addtopic (topic);         ① uses the business method of the JTA transaction          logger.info ("End ...");}  

2. spring references Tomcat's JTA transaction
Tomcat is a servlet container, but it provides the implementation of Jndi,
so the user can be like in a Java EE application server , use Jndi to find the JDBC data source in Tomcat.
in terms of transactional processing, Tomcat does not natively support JTA, but can be achieved by integrating JOTM.
(test environment: Tomcat 5.5+JOTM 2.3)
2.1. Add the required jar file  
Add JOTM the following class pack to the <tomcat installation directory >/common/lib directory:  
jotm.jar 
Jotm_jrmp_ stubs.jar 
jotm_iiop_stubs.jar 
ow_carol.jar 
jta-spec1_0_1.jar 
Jts1_0.ja r 
objectweb-datasource.jar 
xapool.jar 
howl.jar 
connector-1_5.jar 
at the same time, you need to add the JDBC Driver class package for the corresponding database, such as MySQL Mysql.jar.

2.2. Configure JOTM
Create a new carol.properties configuration file, and place it in the <tomcat installation directory >/common/classes directory with the following configuration file contents:
#JNDI调用协议
Carol.protocols=jrmp
# Local RMI Call
Carol.jvm.rmi.local.call=true
# Jndi wrappers that do not use Carol
Carol.start.jndi=false
# do not enable named servers
Carol.start.ns=false
# Naming Factory Classes
Carol.jndi.java.naming.factory.url.pkgs=org.apache.naming
Set Carol.start.jndi to False so that JOTM does not use Carol JNDI Wrapper, which avoids the occurrence of class loading errors.

2.3. Configure the Tomcat environment to configure the data source for Jndi
Add the following in the <tomcat installation directory >/conf/context.xml file:

<!--①:jndi data source--><resource name= "Jdbc/topicds" auth= "Container" type= "Javax.sql.DataSource" factory= "     Org.objectweb.jndi.DataSourceFactory "    username=" root "    password=" 1234 "    driverclassname=" Com.mysql.jdbc.Driver "    url=" jdbc:mysql://localhost:3309/topicdb "    maxactive=" "    maxidle="/> <!--①:jndi data source--><resource name= "Jdbc/postds" auth= "Container" type= "Javax.sql.DataSource" factory= "     Org.objectweb.jndi.DataSourceFactory "    username=" root "    password=" 1234 "    driverclassname=" Com.mysql.jdbc.Driver "    url=" Jdbc:mysql://localhost:3309/postdb "    maxactive=" "    maxidle=" 30 "/ >        

4. The corresponding configuration in spring

<beans xmlns= "Http://www.springframework.org/schema/beans" xmlns:xsi= "http://www.w3.org/2001/ Xmlschema-instance "xmlns:tx=" Http://www.springframework.org/schema/tx "xmlns:jee="/HTTP/ Www.springframework.org/schema/jee "xsi:schemalocation=" Http://www.springframework.org/schema/beans http: Www.springframework.org/schema/beans/spring-beans-2.0.xsd Http://www.springframework.org/schema/tx http://w Ww.springframework.org/schema/tx/spring-tx-2.0.xsd Http://www.springframework.org/schema/jee Http://www.spri Ngframework.org/schema/jee/spring-jee-2.0.xsd "> <jee:jndi-lookup id=" Topicds "Jndi-name=" Java:comp/env/jdbc /topicds "/> <jee:jndi-lookup id=" Postds "jndi-name=" Java:comp/env/jdbc/postds "/> <bean id=" TopicTempla TE "class=" Org.springframework.jdbc.core.JdbcTemplate "> <property name=" dataSource "ref=" Topicds "/> &L t;/bean> <bean id= "posttemplate" class= "Org.springframework.jdbc.core. JdbcTemplate "> <property name=" dataSource "ref=" Postds "/> </bean> <bean id=" Topicdao "Clas s= "Com.baobaotao.dao.jdbc.TopicJdbcDao" > <property name= "jdbctemplate" ref= "Topictemplate"/> </bean > <bean id= "Postdao" class= "Com.baobaotao.dao.jdbc.PostJdbcDao" > <property name= "jdbctemplate" ref= "        Posttemplate "/> </bean> <bean id=" Bbtforum "class=" Com.baobaotao.service.impl.BbtForumImpl ">    <property name= "Topicdao" ref= "Topicdao"/> <property name= "Postdao" ref= "Postdao"/> </bean> <bean id= "Txmanager" class= "Org.springframework.transaction.jta.JtaTransactionManager"/> <tx:annotation- Driven transaction-manager= "Txmanager"/></beans>

3. Using JTA on a specific application server

BEA WebLogic
In an environment that uses WebLogic 7.0, 8.1, or later, you typically prefer WebLogic-specific weblogicjtatransactionmanager classes
To replace the underlying Jtatransactionmanager class.
Because in the WebLogic environment, this class provides full support for the spring transaction definition, exceeding the standard JTA semantics.
You can use the following configuration to achieve your goal:

Its features include support for transaction names, support for defining isolation levels for each transaction, and the ability to properly restore transactions in any environment.

IBM WebSphere
In WebSphere 5.1, 5.0, and 4.x environments, you can use the Spring Webspheretransactionmanagerfactorybean class.
This is a factory class that gets the JTA TransactionManager instance through the static access method of WebSphere (which is different in each version of WebSphere).
Once the JTA TransactionManager instance is obtained through the factory bean,
You can use this instance to assemble a spring jtatransactionmanager bean,
It encapsulates the JTA UserTransaction, which provides enhanced transactional semantics.

<bean id= "WSJTATM"    class= "Org.springframework.transaction.jta.WebSphereTransactionManagerFactoryBean"/ ><bean id= "TransactionManager"    class= "Org.springframework.transaction.jta.JtaTransactionManager" >    <property name= "TransactionManager ref=" Wsjtatm "/>    <!--① referencing WebSphere JTA transaction manager--></bean >

Name Explanation:
JOTM (Java open Transaction Manager) is an open source JTA implementation of ObjectWeb,
It is also part of the open source application server Jonas (Java open Application Server).
Provides the ability to JTA distributed transactions.

Reference:
JTA Transaction Management (i) http://mavin.zhou.blog.163.com/blog/static/114522435200971822334475/
JTA Transaction Management (ii) http://mavin.zhou.blog.163.com/blog/static/114522435200971822912342/

Http://www.cnblogs.com/zjstar12/archive/2012/06/17/2552710.html

Other:
JTA Integrated JOTM or Atomikos configuring distributed transactions (Tomcat application server) http://kb.cnblogs.com/a/2012014/

Spring's support for JTA

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.