簡體   English   中英

休眠雙向一對多插入重復項

[英]hibernate bidirectional one-to-many inserts duplicates

我在這里有親子關系問題。 當我從收款方(孩子方面)堅持下來時,我得到了兩個新孩子而不是一個。

這是休眠映射:

    <set name="children" inverse="true"
        cascade="all,delete-orphan" lazy="true"
        order-by="CHILD_ID desc">
        <key column="PARENT_ID" />
        <one-to-many class="com.mycompany.Child" />
    </set>
    <many-to-one name="parent" class="com.mycompany.Parent" not-null="true">
        <column name="PARENT_ID" />
    </many-to-one>

這是用於將子級添加到雙向關系中的Java代碼:

// Persist logic...
Parent p = myParentService.findById(1);
Child c = new Child();
p.addChild(c);
myChildService.persist(child);

// Inside the parent class...
public void addChild(Child child)
{
    if (this.children == null)
        this.children = new LinkedHashSet<Child>();

    this.children.add(child);
    child.setParent(this);
}

如果我刪除“ this.children.add(child);” 部分,一切正常。 這很令人困惑,因為這里的Hibernate文檔說雙向關系應該以這種方式工作。 我想念什么?

您已在父級集合上啟用了層疊持久化,因此無需在子實體上顯式調用持久化。 如果父級處於托管狀態,則新的子級將在下次事務提交/存在同步時被保留。 您鏈接的示例文檔中未打開Cascade。

暫無
暫無

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

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