我使用MyBatis 3.4.5和Spring 4.1.6。我已经检查了抽象类GenericException(extended Exception(和CustomException(extends GenericException(。我在tx:中为GenericException设置了默认回滚
<tx:advice id="txSetRollBackForCoreExceptionsAdvice" transaction-manager="transactionManager">
<tx:attributes>
<tx:method name="*" rollback-for="RuntimeException,xxx.exceptions.GenericException"/>
</tx:attributes>
</tx:advice>
服务中的方法1:
@Override
public Long push(TimerState timerState) {
try {
return timerStatePushService.pushEvent(timerState);
}catch (Exception e) {
throw new TimerException(e.getMessage());
}
}
服务2:
@Transactional(propagation = Propagation.REQUIRES_NEW)
@Service
public class TimerStatePushServiceBean implements TimerStatePushService {
@Autowired
PushService pushService;
@Override
public Long pushEvent(TimerState timerState) throws GenericException {
return pushService.pushEventById(timerState.getId());
}
如果pushService抛出CustomException(它扩展了GenericException(,我会在Service1中捕获UnexpectedRollbackException。在跟踪日志中,我看到:
12:42:48.677 TRACE {pool-15-thread-1} [o.s.t.i.RuleBasedTransactionAttribute] : Applying rules to determine whether transaction should rollback on xxx.exceptions.CustomException
12:42:48.677 TRACE {pool-15-thread-1} [o.s.t.i.RuleBasedTransactionAttribute] : Winning rollback rule is: null
12:42:48.677 TRACE {pool-15-thread-1} [o.s.t.i.RuleBasedTransactionAttribute] : No relevant rollback rule found: applying default rules
12:42:48.677 DEBUG {pool-15-thread-1} [o.s.j.d.DataSourceTransactionManager] : Global transaction is marked as rollback-only but transactional code requested commit
如果我设置"rollbackFor=GenericException.class",一切都好:
@Transactional(propagation = Propagation.REQUIRES_NEW, rollbackFor = GenericException.class)
@Service
public class TimerStatePushServiceBean implements TimerStatePushService {
@Autowired
PushService pushService;
@Override
public Long pushEvent(TimerState timerState) throws GenericException {
return pushService.pushEventById(timerState.getId());
}
如果我在没有设置rollbackFor的情况下在mehtod"pushEvent"中抛出CustomException,那就没问题了:
@Transactional(propagation = Propagation.REQUIRES_NEW)
@Service
public class TimerStatePushServiceBean implements TimerStatePushService {
@Autowired
PushService pushService;
@Override
public Long pushEvent(TimerState timerState) throws GenericException {
throw new CustomException("msg");
}
我不明白发生了什么。仅供参考:我需要在TimerStatePushService中回滚事务,而不在Service1中回滚事务。
我已经解决了这个问题。我有两个模块:core
和manager
。设置core
时:
<aop:config>
<aop:pointcut expression="within(xxx.core..*) && @within(org.springframework.stereotype.Service)"
id="inCoreServiceCall"/>
<aop:advisor order="1"
advice-ref="txSetRollBackForCoreExceptionsAdvice"
pointcut-ref="inCoreServiceCall"/>
</aop:config>
core
模块中的PushService
、manager
模块中的另一个服务。我添加了manager
模块的设置。