开发者

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开发者_StackOverflow中文版 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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜