两台不同的数据库上完成分布式跨库事务
1 Spring配置文件,jotm-applicationContext-db.xml
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.0.xsd"> <bean id="placeholderConfig" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> <property name="location"> <value>classpath:jotm-db.properties </value> </property> </bean> <bean id="jotm" class="org.springframework.transaction.jta.JotmFactoryBean" /> <bean id="localDatasource" class="org.enhydra.jdbc.pool.StandardXAPoolDataSource" destroy-method="shutdown"> <property name="dataSource"> <bean class="org.enhydra.jdbc.standard.StandardXADataSource" destroy-method="shutdown"> <property name="transactionManager"> <ref local="jotm" /> </property> <property name="driverName" value="${db.driverClassName}" /> <property name="url" value="${db.url}:${db.port};DatabaseName=LOCAL" /> <property name="user" value="${db.username}" /> <property name="password" value="${db.password}" /> </bean> </property> <property name="user" value="${db.username}" /> <property name="password" value="${db.password}" /> <property name="minSize" value="1" /> <property name="maxSize" value="5" /> <property name="checkLevelObject" value="4" /> <property name="jdbcTestStmt" value="select 1" /> </bean> <bean id="foreignDatasource" class="org.enhydra.jdbc.pool.StandardXAPoolDataSource" destroy-method="shutdown"> <property name="dataSource"> <bean class="org.enhydra.jdbc.standard.StandardXADataSource" destroy-method="shutdown"> <property name="transactionManager"> <ref local="jotm" /> </property> <property name="driverName" value="${db.foreign.driverClassName}" /> <property name="url" value="${db.foreign.url}:${db.foreign.port};DatabaseName=${db.name.foreign}" /> <property name="user" value="${db.foreign.username}" /> <property name="password" value="${db.foreign.password}" /> </bean> </property> <property name="user" value="${db.foreign.username}" /> <property name="password" value="${db.foreign.password}" /> <property name="minSize" value="1" /> <property name="maxSize" value="5" /> <property name="checkLevelObject" value="4" /> <property name="jdbcTestStmt" value="select 1" /> </bean> <bean id="local_sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean"> <property name="dataSource"> <ref local="localDatasource" /> </property> <property name="mappingLocations"> <list> <value>classpath:edu/dlut/nihao/**/*.hbm.xml </value> </list> </property> <property name="hibernateProperties"> <props> <prop key="hibernate.dialect"> org.hibernate.dialect.SQLServerDialect </prop> <prop key="hibernate.show_sql">true</prop> </props> </property> </bean> <bean id="foreign_sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean"> <property name="dataSource"> <ref local="foreignDatasource" /> </property> <property name="mappingLocations"> <list> <value>classpath:edu/dlut/nihao/**/*.hbm.xml </value> </list> </property> <property name="hibernateProperties"> <props> <prop key="hibernate.dialect"> org.hibernate.dialect.SQLServerDialect </prop> <prop key="hibernate.show_sql">true</prop> </props> </property> </bean> <bean id="local_personDAO" class="edu.dlut.nihao.lvhl.domain.PersonDAO"> <property name="sessionFactory"> <ref bean="local_sessionFactory" /> </property> </bean> <bean id="foreign_personDAO" class="edu.dlut.nihao.lvhl.domain.PersonDAO"> <property name="sessionFactory"> <ref bean="foreign_sessionFactory" /> </property> </bean> <bean id="personDS" class="edu.dlut.nihao.lvhl.domain.PersonDS"> <property name="foreignDAO" ref="foreign_personDAO"></property> <property name="localDAO" ref="local_personDAO"></property> </bean> <bean id="jotmTransactionManager" class="org.springframework.transaction.jta.JtaTransactionManager"> <property name="userTransaction"> <ref local="jotm" /> </property> <property name="nestedTransactionAllowed" value="true" /> </bean> <bean id="jotmTxAttributeSource" class="org.springframework.transaction.interceptor.NameMatchTransactionAttributeSource"> <property name="properties"> <props> <prop key="transferPerson">PROPAGATION_REQUIRED</prop> </props> </property> </bean> <bean id="jotmAutoproxy" class="org.springframework.aop.framework.autoproxy.BeanNameAutoProxyCreator"> <property name="beanNames"> <value>personDS</value> </property> <property name="interceptorNames"> <list> <value>jotmTransactionInterceptor</value> </list> </property> </bean> <bean id="jotmTransactionInterceptor" class="org.springframework.transaction.interceptor.TransactionInterceptor"> <property name="transactionManager" ref="jotmTransactionManager" /> <property name="transactionAttributeSource" ref="jotmTxAttributeSource" /> </bean> </beans>
2 数据库属性文件,jotm-db.properties,Local和Foreign两个部署在不同服务器上的数据库实例。
#Created by JInto - www.guh-software.de #Wed Aug 25 16:36:01 CST 2010 db.driverClassName=com.microsoft.sqlserver.jdbc.SQLServerDriver db.password=1234 db.port=1433 db.url=jdbc\:sqlserver\://10.87.40.148 db.username=sa db.name.local=LOCAL db.name.foreign=FOREIGN db.foreign.driverClassName=com.microsoft.sqlserver.jdbc.SQLServerDriver db.foreign.port=1433 db.foreign.url=jdbc\:sqlserver\://10.87.40.149 db.foreign.username=sa db.foreign.password=000000
3 hibernate映射文件Person.hbm.xml
<?xml version="1.0"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"> <hibernate-mapping package="edu.dlut.nihao.lvhl.domain"> <class name="edu.dlut.nihao.lvhl.domain.Person" table="Person" select-before-update="false" dynamic-update="false" dynamic-insert="false" optimistic-lock="version"> <id name="id" column="Id" type="java.lang.Long" length="19"> <generator class="assigned"></generator> </id> <property name="name" type="java.lang.String" update="true" insert="true" access="property" column="Name" length="50" not-null="false" /> </class> </hibernate-mapping>
4 数据库表均为Person,定义为:
SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO SET ANSI_PADDING ON GO CREATE TABLE [dbo].[Person]( [Id] [bigint] NOT NULL, [Name] [varchar](50) NULL, CONSTRAINT [PK_Person] PRIMARY KEY CLUSTERED ( [Id] ASC )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] ) ON [PRIMARY] GO SET ANSI_PADDING OFF
5 数据访问层DAO由两个组件构成,接口IPersonDAO和实现类PersonDAO
IPersonDAO.java
package edu.dlut.nihao.lvhl.domain; public interface IPersonDAO { void insertPerson(Object person); void remove(Object person); }
PersonDAO.java
package edu.dlut.nihao.lvhl.domain; import org.springframework.orm.hibernate3.support.HibernateDaoSupport; public class PersonDAO extends HibernateDaoSupport implements IPersonDAO { public void insertPerson(Object person) { getHibernateTemplate().save(person); } public void remove(Object person) { getHibernateTemplate().delete(person); } }
6 实体类 Person.java
package edu.dlut.nihao.lvhl.domain; public class Person { private Long id; private String name; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } }
7 要跨库的业务,以DS为后缀,由接口IPersonDS和实现类PersonDS组成
IPersonDS.java
package edu.dlut.nihao.lvhl.domain; public interface IPersonDS { void transferPerson(Person person) throws Exception; }
PersonDS.java
package edu.dlut.nihao.lvhl.domain; public class PersonDS implements IPersonDS { private IPersonDAO localDAO; private IPersonDAO foreignDAO; public void transferPerson(Person person) throws Exception { localDAO.remove(person); foreignDAO.insertPerson(person); // ExceptionUtil.exceptionOccur(); } public IPersonDAO getLocalDAO() { return localDAO; } public void setLocalDAO(IPersonDAO localDAO) { this.localDAO = localDAO; } public IPersonDAO getForeignDAO() { return foreignDAO; } public void setForeignDAO(IPersonDAO foreignDAO) { this.foreignDAO = foreignDAO; } }
其中 ExceptionUtil.exceptionOccur();
该行代码在运行时抛出数组越界异常,用来测试事务的回滚。
ExceptionUtil.java
package edu.dlut.nihao.lvhl.domain; public final class ExceptionUtil { public static void exceptionOccur() { int[] arr = new int[1]; arr[1] = 0; } }
8 加载Spring的Bean的类JotmContextFactory.java
package edu.dlut.nihao.lvhl.domain.jotm; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class JotmContextFactory { static ApplicationContext ctx = null; public static Object findService(String beanId) { if (ctx == null) { ctx = new ClassPathXmlApplicationContext( new String[] { "jotm-applicationContext-db.xml" }); } return ctx.getBean(beanId); } }
9 测试类JotmTest.java
package edu.dlut.nihao.lvhl.domain.jotm; import edu.dlut.nihao.lvhl.domain.IPersonDAO; import edu.dlut.nihao.lvhl.domain.IPersonDS; import edu.dlut.nihao.lvhl.domain.Person; public class JotmTest { static String PERSON_NAME = "nihao"; static long PERSON_ID = 12; public static void main(String[] args) { IPersonDAO localDao = (IPersonDAO) JotmContextFactory .findService("local_personDAO"); Person person = new Person(); person.setName(PERSON_NAME); person.setId(PERSON_ID); localDao.insertPerson(person); // 测试跨库事务 IPersonDS personDS = (IPersonDS) JotmContextFactory .findService("personDS"); try { personDS.transferPerson(person); } catch (Exception e) { e.printStackTrace(); } } }
10 注意的地方:
10.1异常:
Exception in thread "main" java.lang.StackOverflowError
at java.security.AccessController.doPrivileged(Native Method)
at com.sun.naming.internal.VersionHelper12.getContextClassLoader(VersionHelper12.java:158)
at com.sun.naming.internal.ResourceManager.getFactory(ResourceManager.java:339)
at javax.naming.spi.NamingManager.getURLObject(NamingManager.java:575)
at javax.naming.spi.NamingManager.getURLContext(NamingManager.java:533)
at javax.naming.InitialContext.getURLOrDefaultInitCtx(InitialContext.java:279)
at javax.naming.InitialContext.lookup(InitialContext.java:351)
at org.hibernate.transaction.JTATransactionFactory.getUserTransaction(JTATransactionFactory.java:162)
at org.hibernate.transaction.JTATransactionFactory.getUserTransaction(JTATransactionFactory.java:172)
at org.hibernate.transaction.JTATransactionFactory.getUserTransaction(JTATransactionFactory.java:172)
at org.hibernate.transaction.JTATransactionFactory.getUserTransaction(JTATransactionFactory.java:172)
解决:
spring配置文件jotm-applicationContext-db.xml中sessionFactory项导致
原来配置:
<bean id="local_sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean"> <property name="dataSource"> <ref local="localDatasource" /> </property> <property name="mappingLocations"> <list> <value>classpath:edu/dlut/nihao/**/*.hbm.xml </value> </list> </property> <property name="hibernateProperties"> <props> <prop key="hibernate.dialect"> org.hibernate.dialect.SQLServerDialect </prop> <prop key="hibernate.show_sql">true</prop> </props> </property> <property name="jtaTransactionManager"> <ref local="jotm" /> </property> </bean> <bean id="foreign_sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean"> <property name="dataSource"> <ref local="foreignDatasource" /> </property> <property name="mappingLocations"> <list> <value>classpath:edu/dlut/nihao/**/*.hbm.xml </value> </list> </property> <property name="hibernateProperties"> <props> <prop key="hibernate.dialect"> org.hibernate.dialect.SQLServerDialect </prop> <prop key="hibernate.show_sql">true</prop> </props> </property> <property name="jtaTransactionManager"> <ref local="jotm" /> </property>
应该删除属性jtaTransactionManager,因为在DataSource中已经配置该属性。