HIbernate Can't delete Entity with foreign key. Foreign key gets set to null

后端 未结 2 1880
终归单人心
终归单人心 2021-02-15 06:08

This question has been asked in many forms here but none of the solutions seem to work for me. I\'m trying to delete the parent entity and I want all of the child entities to al

2条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2021-02-15 06:54

    In Hibernate, you need to decide who is owning the relationship. If you have the parent side (ItemCategory) owning the relationship, you will find insertion/deletion of Item+ ItemCategory will involve update of item_id in ItemCategory table (which is what I observed from your exception). In most case it is not preferable. We usually let the children own the relationship. This is done by using mappedBy

    (pseudo-code)

    class Item {
      //...
    
      @OneToMany(mappedBy = "item", cascade=ALL, orphanRemoval=true)
      private Set categories;
    }
    
    class ItemCategory {
      //...
    
      @ManyToOne
      @JoinColumn(name="item_id")
      Item item;
    }
    

    The trick here is mappedBy

提交回复
热议问题