gpt4 book ai didi

java - 从一侧到多侧级联 hibernate

转载 作者:行者123 更新时间:2023-12-04 06:50:05 27 4
gpt4 key购买 nike

我知道之前可能会问这个问题,但我想说得具体一点,

我正在使用没有注释的 hibernate ,所以我的情况是如果我有以下关系:

A 有很多 B,B 有一个 A,这是 A 端的一对多关系,我正在处理包含 B 集的 A 实体,然后在使用 A 在运行时创建、更新 B 时,然后使用 A 保存或更新 A hibernate ,我也希望它保存或更新 B 即级联保存删除,但从 A(一对多)的一侧,我认为它只允许从 B(多对一)一侧

请注意,

最佳答案

我不确定我是否理解这个问题,但绝对可以定义操作以实现一对多关联的级联(请参阅 6.2. Collection mappings 部分)。下面,摘自 Chapter 21. Example: Parent/Child :

21.3. Cascading life cycle

You can address the frustrations of the explicit call to save() by using cascades.

<set name="children" inverse="true" cascade="all">
<key column="parent_id"/>
<one-to-many class="Child"/>
</set>

This simplifies the code above to:

Parent p = (Parent) session.load(Parent.class, pid);
Child c = new Child();
p.addChild(c);
session.flush();

Similarly, we do not need to iterate over the children when saving or deleting a Parent. The following removes p and all its children from the database.

Parent p = (Parent) session.load(Parent.class, pid);
session.delete(p);
session.flush();

However, the following code:

Parent p = (Parent) session.load(Parent.class, pid);
Child c = (Child) p.getChildren().iterator().next();
p.getChildren().remove(c);
c.setParent(null);
session.flush();

will not remove c from the database. In this case, it will only remove the link to p and cause a NOT NULL constraint violation. You need to explicitly delete() the Child.

Parent p = (Parent) session.load(Parent.class, pid);
Child c = (Child) p.getChildren().iterator().next();
p.getChildren().remove(c);
session.delete(c);
session.flush();

In our case, a Child cannot exist without its parent. So if we remove a Child from the collection, we do want it to be deleted. To do this, we must use cascade="all-delete-orphan".

<set name="children" inverse="true" cascade="all-delete-orphan">
<key column="parent_id"/>
<one-to-many class="Child"/>
</set>

Even though the collection mapping specifies inverse="true", cascades are still processed by iterating the collection elements. If you need an object be saved, deleted or updated by cascade, you must add it to the collection. It is not enough to simply call setParent().



引用
  • 6.2. Collection mappings
  • Chapter 21. Example: Parent/Child
  • 关于java - 从一侧到多侧级联 hibernate ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3260767/

    27 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com