3声明式管理Hibernate分布式事务
通过Spring,还可以很方便地切换至另一种事务管理策略。比如需要提供分布式事务管理策略时,只要替换一下配置即可,如代码10.29所示。
代码10.29 appContext-jta.xml
<beans>
<bean id="transactionManager"
class="org.springframework.transaction.jta.JtaTransactionManager">
<property name="sessionFactory" >
<ref bean="sessionFactory" />
</property>
</bean>
<bean id="myDataSource1"
class="org.springframework.jndi.JndiObjectFactoryBean">
<property name="jndiName">
<value>java:comp/env/jdbc/myds1</value>
</property>
</bean>
<bean id="myDataSource2"
class="org.springframework.jndi.JndiObjectFactoryBean">
<property name="jndiName">
<value>java:comp/env/jdbc/myds2</value>
</property>
</bean>
<bean id="sessionFactory1"
class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<property name="dataSource" ref="myDataSource1"/>
<property name="configLocations">
<value>hibernate.cfg1.xml</value>
</property>
</bean>
<bean id="sessionFactory2"
class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<property name="dataSource" ref="myDataSource2"/>
<property name="configLocations">
<value>hibernate.cfg2.xml</value>
</property>
</bean>
<bean id="dao1"
class="daopackage1.DaoImpl">
<property name="sessionFactory" ref="sessionFactory"/>
</bean>
<bean id="dao2"
class="daopackage2.DaoImp2">
<property name="sessionFactory" ref="sessionFactory"/>
</bean>
</beans>
<bean id="business" class="businesspackage.BusinessFacadeImpl">
<property name="dao1">
<ref bean="dao1"/>
</property>
<property name="dao2">
<ref bean="dao2"/>
</property>
</bean>
<bean id="businessProxy"
class="org.springframework.transaction.interceptor.TransactionProxyFactoryBean">
<property name="transactionManager">
<ref bean="transactionManager" />
</property>
<property name="target">
<ref bean="business" />
</property>
<property name="transactionAttributes">
<props>
<prop key="business*">PROPAGATION_REQUIRED</prop>
<prop key="someOtherBusiness*">PROPAGATION_MANDATORY</prop>
</props>
</property>
</bean>
</beans>
可以看到,对于横跨多个Hibernate SessionFacotry的分布式事务,只需简单地将JtaTransactionManager和LocalSessionFactoryBean的定义结合起来就可以了,其中每个DAO通过bean属性得到各自的SessionFactory引用。
说明:如果所有底层数据源都是支持事务的容器,那么只需要对一个业务对象应用JtaTransactionManager策略,该对象就可以横跨多个DAO和多个Session Factory来划分事务了。使用Spring的最大好处就是,可通过配置来声明式地管理事务,无需对应用代码作任何改动。
posted on 2009-07-27 01:52
jadmin 阅读(103)
评论(0) 编辑 收藏