We had a similar need in our project and found org.springframework.transaction.support.TransactionSynchronizationManager to assist us. Since the entity could get rolled back if the transaction rolls back, we added the following method to execute code after a transaction commits:
void executeAfterCommit(Closure c) {
TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronizationAdapter() {
@Override
void afterCommit() {
c.call()
}
})
}
We then call this method by passing it a closure with the code we want to call and when the current transaction is finished, the closure is invoked. This seems to work for us, but be careful, there are a few caveats:
- If you throw out of this method, it can cause odd behavior. To work around this, we have another version of the method that forks an async thread to execute the closure to ensure it doesn't affect the transaction that's committing.
- You can't call this method from the closure since the transaction will have already committed (it won't trigger again)
I don't think we've tried calling it from the events so I'm unsure of the behavior in your case, but I think it would work. We typically call this where we call save() instead. Maybe it will help ...
-James