Prevent Hibernate from deleting orphaned entities while merging an entity having entity associations with orphanRemoval set to true

后端 未结 2 476
谎友^
谎友^ 2020-12-10 11:13

Taking a very simple example of one-to-many relationship (country -> state).

Country (inverse side) :

@OneToMany(mappedBy = \"country         


        
2条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-10 11:39

    As soon as your referenced entity can be used in other parents, it gets complicated anyway. To really make it clean, the ORM had to search in the database for any other usages of the removed entity before deleting it (persistent garbage collection). This is time consuming and therefore not really useful and therefore not implemented in Hibernate.

    Delete orphans only works if your child is used for a single parent and never reused somewhere else. You may even get an exception when trying to reuse it to better detect the misuse of this feature.

    Decide whether you want to keep delete orphans or not. If you want to keep it, you need to create a new child for the new parent instead of moving it.

    If you abandon delete orphans, you have to delete the children yourself as soon as they are not referenced anymore.

提交回复
热议问题