捕获异常后事务回滚

Amb*_*ari 3 java spring transactions

有没有办法在使用声明性事务管理捕获异常后回滚事务。我有这段代码。

@Component
@Transactional(rollbackFor = EvictionException.class)
Public class Eviction{

@Autowired
private Alerter alerter;

@Scheduled(cron = "${evictor.cron.expression}")
public void evictObjectFromDatabase(){
try{
   ....
   DO SOME DELETION QUERIES
}catch(Exception ex){
   alerter.produceAlert("Failed to delete entries from database");
}
}
}
Run Code Online (Sandbox Code Playgroud)

如果删除时产生异常,我需要发出警报,由另一个团队监视 Swing UI。我还需要回滚事务,但使用 rollBackFor = Exception.class 不起作用。

sol*_*4me 7

您需要@Transactional(rollbackFor = Exception.class)在 catch 块中注释您的方法并抛出异常(以便事务代理可以检测到异常并因此回滚)例如

try{
   ....
   DO SOME DELETION QUERIES
}catch(Exception ex){
   alerter.produceAlert("Failed to delete entries from database");
   throw ex;// this is important
}
Run Code Online (Sandbox Code Playgroud)