如何使hibernate单向多对多关联可更新?

时间:2015-03-02 10:29:41

标签: java hibernate many-to-many updates

我有两个实体 - CategoryAttributeCategory可以有多个相关属性,Attribute可以与任意数量的类别相关联。关联应仅在Category方可用 - Attribute对象不知道与其相关的类别。

因此,我将此关联建模为单向多对多:

Category.hbm.xml

<class name="Category" table="category" proxy="ICategory" entity-name="category">
  <id name="id" column="id" unsaved-value="null"><generator class="identity" /></id>
  ...some properties...
  <bag name="relatedAttributes" table="category_attribute" fetch="select">
    <key column="id_category" />
    <many-to-many column="id_attribute" entity-name="attribute" />
  </bag>
</class>

和Attribute.hbm.xml

<class name="Attribute" table="attribute" proxy="IAttribute" entity-name="attribute">
  <id name="id" column="id" unsaved-value="null" ><generator class="identity" /></id>
  ...some properties...
</class>

映射与当前数据完美匹配,直到需要更新。我只想做一些简单的事情:

ICategory c = (ICategory) session.get("category", 1);
c.getRelatedAttributes().add((IAttribute) session.get("attribute", 2));
session.update("category", c);

如何使此关联更新?

1 个答案:

答案 0 :(得分:0)

终于完成了。影响行为的变化:

<bag name="relatedAttributes" table="category_attribute" fetch="select" inverse="false" cascade="save-update">
  ...
</bag>

并且不要忘记在操作后致电session.flush()

相关问题