简体   繁体   中英

How to delete a many-to-many association between two entities?

Suppose I have two entities and a bi-directional many-to-many relation between them mapped in Hibernate.

The xml configuration looks like this in both classes:

<hibernate-mapping>
    <class name="com.example.MyEntity">
        <set name="myOtherEntities" cascade="all-delete-orphan">
            <key column="entity_id"/>
            <many-to-many column="my_other_entity_id" class="com.example.OtherEntity" />
        </set>
    </class>
</hibernate-mapping>

How can I terminate only the association between them without deleting any of the entities?

If I clear() the set in MyEntity and call Session.flush() then the MyOtherEntity objects get deleted but I only want to clear the records in the join table.

I think it's the delete orphan property that trigger the deletion for MyOtherEntity .

Should be replaced by cascade="all"

Regards.

Addendum : Hibernate doc indicate in chapter 11 that cascade all-delete-orphan should not be used with ManytoMany relations.

There are 2 ways using which you can do this.

1) Using Hibernate Native Query 2) Using Hibernate createSQLQuery()

The correct setting in this scenario is cascade="none" .

Hibernate in many-to-many relations has to work with 3 tables. MyEntity , OtherEntity and pairing table MyEntity-OtherEntity .

Pair table

Once we create the relation by adding MyEntity instance into the OtherEntity collection and vice versa, Hibernate will hiddenly insert the record into pairing table. Once we remove some instance form the collection, Hibernate will remove the record from pairing table.

This is done, with the setting cascade="none" . Becuase it is the only way how to handle that. There is no cascading from the perspective of the pairing table

The cascading

Any cascading applied on many-to-many relation, does not apply to pairing table, but to the second end. In most cases, this is what we do not want. We should have separated DAO for MyEntity management and OtherEntity management.

In rare cases, when during update of one end, we want to insert, update or even delete the other... we can use cascading. But this is not our case.

Use this setting in this scenario

<set name="myOtherEntities" cascade="none">

See more 8.3.4. Many-to-many

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM