Hibernate - clearing a collection with all-delete-orphan and then adding to it causes ConstraintViolationException

空扰寡人 提交于 2019-12-04 00:18:57
Eran Medan

I guess there is no alternative to flushing

From here:

Hibernate is violating a unique constraint!

Hibernate isn't quite as clever with unique constraints as it is with foreign keys. Sometimes you might need to give a little hint.

A unique constraint violation could occur if two objects are both being updated, one is "releasing" a value and the other is "obtaining" the same value. A workaround is to flush() the session manually after updating the first object and before updating the second.

(This kind of problem occurs rarely in practice.)

If you want to avoid flushing the session here, try to replace the whole list (new List<Bar>() instead of Clear()). Hibernate should actually remove all the items in one shot before adding new. Just a try, not sure if it works.

If you are using oracle, you could also use deferrable constraints to postpone the checking of the constraints until the transaction is committed. Not sure if/how this is supported by other databases.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!