0
votes

In Spring based application, Transaction Manager is responsible for committing or rolling back SQL transactions. My application uses a custom cache for some part of persistent data. This cache is not managed by Spring nor Hibernate.

If a SQL transaction encounters errors and must be rolled back, then cache modifications should be rolled back as well.

My question is, how to register an event listener or callback which will call my cache.evict() method when Spring Transaction Manager rolls back a transaction?

2

2 Answers

2
votes

You can use TransactionSynchronizationAdapter for this. For reference, you can look at this: Spring - commit JMS Transaction after JPA transaction

In the answer given in the link, the synchronization is registered for afterCommit. In your case, it would be afterCompletion. In that implementation, you will need to check if the transaction is in a rolled back state and do the cache eviction.

0
votes

There are lots of ways of doing this...

  1. You can use application events if you want... Application Events in Spring Framework 4.2
  2. You can throw a custom runtime exception and you can handle it in your exception handler (if you're using spring MVC). but here I don't recommend to do any important operations like clearing of cache here... Exception handling in Spring MVC
  3. You can use a combination of #1 and #2. You can send an event that will eventually throw a runtime exception that you handle it in UI (spring mvc or whatever you use). This is how I would do it
  4. You can throw an exception and anyone calling your bean will get the custom transaction exception you want and will have to deal with notification... I don't recommend this