Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hibernate PostInsertEventListeners -Use Same Transaction as insert?

I have some hibernate code that performs an insert into the database, and on completion of that insert a customized PostInsertEventListener is fired. (Essentially a trigger to ensure that other records are updated appropriately)

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

I have heard that you can use javax.transaction.Syncronization and Hibernate's transaction.registerSyncronization() methods to do this, but there is no examples of usage anywhere that I can find.

Any help is appreciated.

like image 205
Mal Avatar asked Mar 04 '10 00:03

Mal


1 Answers

I dont think this is possible.

If I understand, you want to execute some code only if the transaction completed successfully (was commited). However, if the transaction is commited, you can't do something else in the same transaction since it's ended.

What you could do however is use a PreInsertEventListener which is called within the transaction (before the commit). The event listener will fire event if the transaction fail (since we don't know until commit if the transaction will succeed) but anything you modify in the listener will not be stored in the database if the transaction fail. Check https://www.hibernate.org/hib_docs/v3/api/org/hibernate/event/EventListeners.html for the list of listeners.

One warning though. You should not do too much data modification in a listener. Especially, you should not trigger any lazy loading of collections.

like image 69
Manuel Darveau Avatar answered Oct 18 '22 20:10

Manuel Darveau