I have a class implementing Hibernate PostInsertEventListener which is tied to the Hibernate SessionFactory via Spring. The interceptor is specified for post-insert event type . This interceptor gets invoked whenever I perform a session.save(entity). However, the execution happens before the transaction is flushed. This is problematic if the database throws an exception.
Question:
Is there a way I can specify to invoke an interceptor after the session.flush() has been called?
I tried doing insertEvent.getSession().flush() within the event listener but that produces a primary key violation exception since the id was not yet set.
I have not yet explored the registerSynchronization way because it seems like I am missing some basic configuration. The transaction manager being used is org.springframework.orm.hibernate3.HibernateTransactionManager and the transactional boundaries are specified by the @Transactional annotation. Hibernate version is 3.6
Current solution:
Store the Post(Insert|Update|Delete)Event in a Map with Session as the key. Get the event from the map in the FlushEventListener for the Session and process the event.
The map used is a Guava Cache with an expiration interval set to minutes. This will catch the case where the flush() fails because of a SQLException and the entry for that session needs to be removed from the map.