how to define an inverse cascade delete on a many-to-one mapping in hibernate

后端 未结 2 511
我寻月下人不归
我寻月下人不归 2020-12-09 04:39

I have two classes A and B. Many B\'s can have association with a single A, hence a many-to-one relationship from B to A. I\'ve mapped the relationship like:



        
相关标签:
2条回答
  • 2020-12-09 04:53

    Hibernate only cascades along the defined associations. If A knows nothing about Bs, nothing you do with A will affect Bs.

    Pascal's suggestion is, therefore, the easiest way to do what you want:

    <class name="A" table="tbl_A">
      ...
      <set name="myBs" inverse="true" cascade="all,delete-orphan">
        <key column="col1"/>
        <one-to-many class="B"/>
      </set>
    </class>
    
    <class name="B" table="tbl_B">
      ...
      <many-to-one name="a" class="A" column="col1" not-null="true"/>
    </class>
    

    Note that setting cascade="delete" on B as you have it in your original code will NOT do what you want - it tells Hibernate to "delete A if B is deleted" which is likely to result in constraint violation (if there are any other Bs linked to that A).

    If you absolutely cannot add a collection of Bs to A (though I can't really think of the circumstances where that'd be the case), your only other alternative is to define cascade delete from A to B at the foreign key level; your Bs will then be deleted when your A is deleted.

    This is a rather ugly solution, however, because you have to be extremely careful of how you delete A in Hibernate:

    1. Session must be flushed prior to deleting A (having pending updates to B may result in an error or A and some Bs being re-inserted behind the scenes)
    2. All Bs linked to your A (and since you're not maintaining the relationship from A side that means all Bs) must be evicted from all active sessions and 2nd level cache.
    0 讨论(0)
  • 2020-12-09 04:58

    I think you need to cascade="all,delete-orphan" from A to B's with a one-to-many association.

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