簡體   English   中英

如何使hibernate單向多對多關聯可更新?

[英]How to make hibernate unidirectional many-to-many association updateable?

我有兩個實體 - CategoryAttribute Category可以具有多個相關屬性, 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);

如何使這種關聯可更新?

終於完成了。 影響行為的變化:

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

並且不要忘記在操作之后調用session.flush()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM