【发布时间】:2016-07-02 00:12:58
【问题描述】:
我有一个使用 2 个不同数据源的场景。
数据源 1 服务类(启用事务)调用数据源 2 服务类方法(启用事务但使用数据源 2)
代码如下。我的要求是,当我们在此层次结构中调用时,如何在单独的事务中运行 persistOneByOne()。如果发生异常,请不要保留该记录,但由于它在 for 循环中继续处理其他记录。 我如何实现这种行为。
// 服务类 2 使用由 aop 启用的事务处理的 datasource-1
public class DataSource1ServiceClass1{
DataSource2OtherServiceClass service2;
public void processData(){
service2.prepareAndPeristData();
}
}
// 服务类 2 使用不同的数据源,称为 datasource-2,它也是由 aop 启用的事务
public class DataSource2OtherServiceClass{
public void prepareAndPeristData(){
try{
for(int i=0;i<10;i++)
{
// pre processing before persisting a single record
persistOneByOne();
}
}catch (Exception e){
log.error("Error occurred.. so didn't persist record as expected"};
}
public void persistOneByOne()
{
dao.persist();
}
}
配置xml文件:
<bean id="txManager"
class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource" />
</bean>
<tx:advice id="txAdvice" transaction-manager="txManager">
<tx:attributes>
<tx:method name="*" />
</tx:attributes>
</tx:advice>
<aop:config>
<aop:pointcut id="allServices"
expression="execution(* .service.impl.*.*(..))" />
<aop:advisor advice-ref="txAdvice" pointcut-ref="allServices" />
</aop:config>
<bean id="txManager2"
class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="otherDataSource" />
</bean>
<tx:advice id="txAdvice2" transaction-manager="txManager2">
<tx:attributes>
<tx:method name="*" />
</tx:attributes>
</tx:advice>
<aop:config>
<aop:pointcut id="allOtherServices"
expression="execution(* .service2.impl.*.*(..))" />
<aop:advisor advice-ref="txAdvice2" pointcut-ref="allOtherServices" />
</aop:config>
我如何实现persistOneByOne() 在其自己的事务中运行。如果发生异常回滚该单行。
【问题讨论】:
标签: transactions spring-transactions