I have a spring boot application using JPA and I would like to be notified when a JPA Transaction is commited. I know that there is the @TransactionalEventListener for managing events related to transaction but it is for events published by the app code.
I need to be notified when any Transaction is commited. Do you know if there is any global event for this published by the JPA layer (like an ApplicationEvent)?
There is no such event, but it is easy to make, for example like this:
public class TransactionCommitEvent implements Serializable {
private final TransactionExecution transaction;
private final Throwable commitFailure;
public TransactionCommitEvent(TransactionExecution transaction, Throwable commitFailure) {
this.transaction = transaction;
this.commitFailure = commitFailure;
}
}
@Component
public class TransactionCommitListener implements TransactionExecutionListener {
private final ApplicationEventPublisher publisher;
public TransactionCommitListener(ApplicationEventPublisher applicationEventPublisher) {
this.publisher = applicationEventPublisher;
}
@Override
public void afterCommit(TransactionExecution transaction, Throwable commitFailure) {
publisher.publishEvent(new TransactionCommitEvent(transaction, commitFailure));
}
}