Hibernate Unidirectional Parent/Child relationship - delete() performs update on child table instead of delete

后端 未结 2 820
余生分开走
余生分开走 2020-12-16 03:47

If I delete a record from the Parent table I want the corresponding records in the child table to be deleted. How can I make Hibernate delete from the Child tabl

相关标签:
2条回答
  • 2020-12-16 04:14

    (Note: This has been raised as an incorrect answer by two users).

    Hibernate docs say you can just mark the key column as not-null="true":

    <list name="charityTransferItemList" cascade="all,delete-orphan" lazy="false">
            <key column="TSF_NO" not-null="true" />
            <list-index column="TSF_SEQ_NO"/>
            <one-to-many class="CharityTransferItem" />
    </list>
    

    From Hibernate doc on collections:

    If the foreign key column of a association is declared NOT NULL, you must declare the mapping not-null="true" or use a bidirectional association with the collection mapping marked inverse="true". See the discussion of bidirectional associations later in this chapter for more information.

    I also think there is a typo in your cascade style (all-delete-orphan should be all,delete-orphan).

    0 讨论(0)
  • 2020-12-16 04:15

    I encountered this error all the time.

    Just put an inverse="true" on the relationship and your problem will go away!

    <list name="charityTransferItemList" inverse="true" cascade="all-delete-orphan" lazy="false" >
            <key column="TSF_NO" />
            <list-index column="TSF_SEQ_NO"/>
            <one-to-many class="CharityTransferItem" />
        </list>
    

    Basically the inverse will tell hibernate the child cannot exist without a parent, thereby causing hibernate to delete the child.

    Having said that, you'll also need to remove the charityTransfer object from the collection in the parent as well.

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