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

前端 未结 1 841
隐瞒了意图╮
隐瞒了意图╮ 2020-12-11 06:09

Important Notice : If you are reading this post, then consider looking into this post too for in-depth discussions.


It is a quite usual practi

相关标签:
1条回答
  • 2020-12-11 06:54

    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.

    0 讨论(0)
提交回复
热议问题