Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Transaction RollBack after catching exception

Is there any way to rollback the transaction after catch the exception using declarative transaction management. I have this piece of code.

@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");
}
}
}

If a exception is produced while deletion, i need to raise an alert which another team monitors of a swing UI. Also i need to rollback the transaction but using the rollBackFor = Exception.class does not works.

like image 617
Ambuj Jauhari Avatar asked Feb 05 '26 05:02

Ambuj Jauhari


1 Answers

You need to annotate your method with @Transactional(rollbackFor = Exception.class) and in catch block throw the exception(So that transactional proxy can detect the exception and Hence rollback) E.g.

try{
   ....
   DO SOME DELETION QUERIES
}catch(Exception ex){
   alerter.produceAlert("Failed to delete entries from database");
   throw ex;// this is important
}
like image 118
sol4me Avatar answered Feb 06 '26 19:02

sol4me



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!