简体   繁体   中英

hibernate one-to-many relationship not updating correctly

I have two tables Item and Property and one item can have multiple properties. I have modeled it correctly (i think) in hibernate and when loading the ItemModel object, all the properties load properly.

The problem is when I am trying to delete properties and then save it, the properties just get added to the existing ones.

ItemModel m = ...;
m.getPropertySet().size() // returns 5 initially
m.getPropertySet().clear();
// some update function which adds properties
m.getPropertySet().size(); // returns 1
...currentSession().saveOrUpdate(m);

What happens is that now the database has 6 properties for that category instead of 1. What should I do to make this work?

The model for Item's mapping to properties looks something like this

<set name="propertySet" cascade="all">
    <key column="item_id" not-null="true"/>
    <one-to-many class="Property"/>
</set>

Use cascade="all-delete-orphan" . See the first example in the reference guide for a walkthrough of relationships like this. Also, if this is a bidirectional one-to-many , then this side (the set) should be mapped with inverse="true" so that the relationship is determined solely based on the other side of the relationship.

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