Delete child in one-to-many relation throws ObjectDeletedException

泄露秘密 提交于 2019-12-04 04:02:31

What you may be missing is that Hibernate automatically maintains state for entities that have been loaded and exist in Session, meaning it will persist any changes made to them irregardless of whether you explicitly invoke "update()" method.

Considering your scenario, if you have loaded Organization and its employees set and are now trying to delete one of those employees, Hibernate is telling you (by throwing ObjectDeletedException) that it will re-save deleted employee when it will save Organization because you've declared that saving or updating should be cascaded from organization down to employees in its set.

The proper way to handle this would be to remove said employee from organization's employees set before deleting it thus preventing cascaded re-save.

Edit (based on updated question):

Organization owns collection of employees. Cascade always follows the association - you've declared it on Organization side, so changes (save / update) are propagated down to Employee level. As long as particular Employee instance is a member of employees collection of any Organization entity that lives in session, it will be saved (or re-saved, so Exception is thrown) when session is flushed / closed.

The fact that association is mapped from Employee side (e.g. organization_id column resides in Employee table) is irrelevant here; it could have been mapped via join table with the same results. Hibernate maintains "state" via session and when you're trying to delete Employee without removing it from Organization.employees you're giving Hibernate conflicting instructions (since it's still alive - and has to be saved - in one place but is deleted in the other), hence the exception.

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