Hibernate: How to ensure that a parent is not deleted when all its child entities are?

前端 未结 2 2077
说谎
说谎 2021-01-26 08:22

I am deleting entities and hence rows from my database.

I do want to delete a certain entity and all of its child rows. However, I

2条回答
  •  悲哀的现实
    2021-01-26 08:36

    Currently, when I delete dog entitie(s), its related Kennel entity is also being deleted.

    The reason being you have cascade=CascadeType.ALL set on ManyToOne annotation. With this we are telling the ORM that when we delete (or any other operation) Dog it should propagate the same operation to the Kennel entity as well.

    Remove cascade attribute in ManyToOne(cascade = CascadeType.ALL ).
    

    Can I keep the @oneToMany relationship shown in kennel the same?

    Few changes you might want to consider.

    • No need of having JoinColumn annotation at both oneToMany and ManyTone side.
    • Consider using mappedBy="kennel" attribute in OneToMany annotation and remove JoinColum annotation on OneToMany side. This makes ManyToOne the owning side and is also more efficient from SQLs that gets generated when you persist kennel entity. You can check it yourself by enabling show_sql.
    • Regarding cascade attribute on OneToMany whether to set it to ALL or MERGE or PERSIST, MERGE depends on which operations on parent entity you want to propagate to child entity.
    • Not sure if you have already implemented scaffolding code/methods to add/update the oneToMany relationship. If not, it is a good idea to implement them because that ensures the association is updated on both the ends. Refer to scaffolding code if needed.

提交回复
热议问题