简体   繁体   English

休眠一对多关系无法正确更新

[英]hibernate one-to-many relationship not updating correctly

I have two tables Item and Property and one item can have multiple properties. 我有两个表Item和Property,一个项目可以具有多个属性。 I have modeled it correctly (i think) in hibernate and when loading the ItemModel object, all the properties load properly. 我已经在休眠模式下正确建模(我认为),并且在加载ItemModel对象时,所有属性均正确加载。

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? 现在发生的情况是,该数据库现在具有该类别的6个属性,而不是1个。我应该怎么做才能使其工作?

The model for Item's mapping to properties looks something like this Item映射到属性的模型看起来像这样

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

Use cascade="all-delete-orphan" . 使用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. 另外,如果这是双向一对多的 ,则应将此面(集合)映射为inverse="true"以便仅根据关系的另一面确定关系。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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