![](/img/trans.png)
[英]Using two transaction managers and session factories with spring & hibernate annotations
[英]Spring @Transactional on one service method spanning over two Hibernate transaction managers
我想知道是否可以在一种服务方法中使用两个事务管理器。 因为由于客户端mysql db配置的限制,我们在一个数据库中有2个不同的数据源,即每个模式一个user/pwd/url。 这就是为什么我必须配置两个事务管理器。 现在,当涉及到服务实现时,我遇到了问题。 请参阅以下代码:
public class DemoService{
...
@Transactional(value = "t1")
public doOne(){
doTwo();
}
@Transactional(value = "t2")
public doTwo(){
}
...
}
如果我使用此代码模式,我总是会遇到异常
org.hibernate.HibernateException: No Session found for current thread
如果我分别运行这两种方法,它工作正常。 我错过了什么? 或者这里还有其他工作? 任何意见,将不胜感激。
顺便说一句:我的一些配置
<bean id="sessionFactorySso" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="mappingLocations">
<list>
<value>classpath*:sso.vo/*.hbm.xml</value>
</list>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.show_sql">true</prop>
<prop key="generateDdl">true</prop>
<prop key="hibernate.dialect">${dialect} </prop>
</props>
</property>
<property name="dataSource" ref="dataSourceSso"/>
</bean>
<bean id="dataSourceSso" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close">
<property name="driverClass" value="${driver}"/>
<property name="jdbcUrl" value="${sso.url}"/>
<property name="user" value="${sso.username}"/>
<property name="password" value="${sso.password}"/>
<!-- these are C3P0 properties -->
<property name="acquireIncrement" value="2" />
<property name="minPoolSize" value="1" />
<property name="maxPoolSize" value="2" />
<property name="automaticTestTable" value="test_c3p0" />
<property name="idleConnectionTestPeriod" value="300" />
<property name="testConnectionOnCheckin" value="true" />
<property name="testConnectionOnCheckout" value="true" />
<property name="autoCommitOnClose" value="true" />
<property name="checkoutTimeout" value="1000" />
<property name="breakAfterAcquireFailure" value="false" />
<property name="maxIdleTime" value="0" />
</bean>
<bean id="transactionManagerSso" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactorySso"/>
<qualifier value="sso" />
</bean>
<tx:annotation-driven transaction-manager="transactionManagerSso" />
因为您想在一个事务中登记两个数据源,所以您需要 XA(Global) Transaction。
因此,您需要:
你有几个选择:
除了 Vlad 的解决方案(#4)之外,所有这些都有可能使数据库处于不一致的状态。 您需要使用 JTA/XA/两阶段提交来确保在其中一个 TX 管理器在提交时引发异常的情况下的一致性。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.