Hibernate PostInsertEventListeners - use the same transaction as insert?

I have some hibernation code that does an insert into a database, and when that insert completes, the custom PostInsertEventListener is launched. (This is essentially a trigger to ensure that other records are properly updated)

What I need to do is make the code inside the EventListener use the same transaction as the original insert, so if the insert is not completed successfully, the EventListener will not start.

I heard that you can use javax.transaction.SyncronizationHibernate methods and transaction.registerSyncronization()for this, but there are no usage examples anywhere I can find.

Any help is appreciated.

+5
source share
1 answer

I do not think that's possible.

If I understand, you want to execute some code only if the transaction completed successfully (was completed). However, if the transaction is completed, you cannot do anything else in the same transaction because it has ended.

However, you can use the PreInsertEventListener, which is called inside the transaction (before commit). An event listener will fire an event if the transaction fails (since we don’t know before committing if the transaction is successful), but everything that you change in the listener will not be stored in the database if the transaction fails. Check https://www.hibernate.org/hib_docs/v3/api/org/hibernate/event/EventListeners.html for a list of listeners.

. . , - .

+3

All Articles