I must perform an insert in a special global temporary table before the transaction commit.
This is due to an older design of the database that use this table to perform audit operations using triggers on every business table. Another software written in C use this pattern to perform audit with low impact on the code:
- insert audit data in the temporary table when the connection is established
- perform various insert/update, trigger will link these operation with the audit data
- commit: the audit date are flushed from the temporary table
Now I have a Spring Boot + JPA (Hibernate) application that start to use the same database and I need to reproduce this pattern. However with the Spring + JPA abstraction of the transaction, I struggle to find a way to replicate this behavior.
I need to perform the insertion of the audit data when a transaction is created (or just before it is committed). I've checked this promising TransactionalEventListener, but it looks like I must declare a publisher and fire the event manually in each service, like in the following example:
@Service
public class CustomerService {
private final CustomerRepository customerRepository;
private final ApplicationEventPublisher applicationEventPublisher;
public CustomerService(CustomerRepository customerRepository, ApplicationEventPublisher applicationEventPublisher) {
this.customerRepository = customerRepository;
this.applicationEventPublisher = applicationEventPublisher;
}
@Transactional
public Customer createCustomer(String name, String email) {
final Customer newCustomer = customerRepository.save(new Customer(name, email));
final CustomerCreatedEvent event = new CustomerCreatedEvent(newCustomer);
applicationEventPublisher.publishEvent(event);
return newCustomer;
}
}
As you can see in this sample, the service declare an ApplicationEventPublisher
and need to call applicationEventPublisher.publishEvent(event);
after each update/insert.
This is not fulfilling my needs: I really need to be able to do this operation before every commit() and this must be automatic for all services and repositories.
I've started to work on an AOP based solution, but I feel like its an overkill.
So is there any simple solution to perform some operation before any commit in a Spring Boot + JAP context?