Setting orphanRemoval to true while migrating children from their parent to another parent

人盡茶涼 提交于 2019-11-28 12:21:33
Dragan Bozanovic

This is documented in the JPA specification.

Section 3.2.4 (excerpt):

The semantics of the flush operation, applied to an entity X are as follows:

  • If X is a managed entity, it is synchronized to the database.
    • For all entities Y referenced by a relationship from X, if the relationship to Y has been annotated with the cascade element value cascade=PERSIST or cascade=ALL, the persist operation is applied to Y

Section 3.2.2 (excerpt):

The semantics of the persist operation, applied to an entity X are as follows:

  • If X is a removed entity, it becomes managed.

orphanRemoval JPA javadoc:

(Optional) Whether to apply the remove operation to entities that have been removed from the relationship and to cascade the remove operation to those entities.

orphanRemoval Hibernate docs:

If an entity is removed from a @OneToMany collection or an associated entity is dereferenced from a @OneToOne association, this associated entity can be marked for deletion if orphanRemoval is set to true.

So, you remove the employee E from the department D1 and add her to the department D2.

Hibernate then synchronizes the department D1 with the database, sees that E is not in the list of employees and marks E for deletion. Then it synchronizes D2 with the database and cascades PERSIST operation to the list of employees (section 3.2.4). Since E is now in this list, the cascade applies on it and Hibernate un-schedules the delete operation (section 3.2.2).

You may want to look at this question as well.

"What happens, if orphanRemoval is set to true on the inverse side of such relationships?"

You have already set it on the inverse side (the inverse side is the one which declares mappedBy). If you mean what if it were set on the other side (@ManyToOne in this case), then it would not make sense and that's why there is no such an attribute in @ManyToOne and @ManyToMany.

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