Hibernate @ManyToOne remove entry at One side, set FK to NULL at Many side

送分小仙女□ 提交于 2019-12-06 09:42:44

There is no automatic way of setting all the foreign keys to null when some entity is removed. You have to explicitely get all the authors of the department, set their departement to null, and then remove the department.

You could also use a bulk update query to do this:

update Author a set a.department = null where a.department = :department

(and thus have just one query instead of n + 1), but be aware that the version field won't be updated, that there won't be any optimistic locking check, and that the already loaded departments of the session won't be affected (in memory) if you do so.

Note that you shouldn't have an ObjectNotFoundException when you're deleting an entity referenced by another one. Instead, you should enable a foreign key constraint in the database so that the removal of the department fails if there is still an author referencing it. That way, your data stays in a coherent state.

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