开发者

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 funct开发者_运维百科ion 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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜