gpt4 book ai didi

java - 为什么多对一双向关联需要update和insert设置为false

转载 作者:太空宇宙 更新时间:2023-11-04 07:08:38 26 4
gpt4 key购买 nike

Hibernate document说如果我想使用列表,那么我需要设置 update="false"和 insert="false" 的属性。

请告诉我为什么需要这些属性以及它们有何用处?

If you use a List, or other indexed collection, set the key column of the foreign key to not null. Hibernate will manage the association from the collections side to maintain the index of each element, making the other side virtually inverse by setting update="false" and insert="false":

<class name="Person">
<id name="id"/>
...
<many-to-one name="address"
column="addressId"
not-null="true"
insert="false"
update="false"/>
</class>

<class name="Address">
<id name="id"/>
...
<list name="people">
<key column="addressId" not-null="true"/>
<list-index column="peopleIdx"/>
<one-to-many class="Person"/>
</list>
</class>

我也浏览过这篇文章Setting update and insert property in Hibernate ,但是当我编写一个简单的程序来创建和保存我的 Person 和 Address 对象时,我可以看到 hibernate 本身插入和更新了 addressId 属性:

Hibernate: insert into Address (addressId) values (?)
Hibernate: insert into person1 (addressId, peopleId, personId) values (?, ?, ?)
Hibernate: insert into person1 (addressId, peopleId, personId) values (?, ?, ?)

09:19:08,526 DEBUG AbstractCollectionPersister:1205 - Inserting collection: [partc.onetomany1.Address.people#156]
Hibernate: update person1 set addressId=?, peopleId=? where personId=?
Hibernate: update person1 set addressId=?, peopleId=? where personId=?

但根据 JB Nizet 给出的评论和 Thomas ,这不应该发生。如果我误解了这个概念,请告诉我。

最佳答案

考虑 Hibernate 文档中的示例。我可以尽力提供帮助。

@Entity
public class Troop {
@OneToMany(mappedBy="troop")
public Set<Soldier> getSoldiers() {
...
}

@Entity
public class Soldier {
@ManyToOne
@JoinColumn(name="troop_id")
public Troop getTroop() {
...
}

在这种情况下,您的表结构将是

**Troop**
Troop_id | Troop_desc
T1 | Troop 1
T2 | Troop 2

**Soldier**
Soldier_Id | Troop_Id | Soldier_Name
S1 | T1 | XYZ
S2 | T2 | PQR

**考虑在上述情况下,您需要添加一个士兵,函数调用将是

1) 创建带有部队的士兵并将其保存在士兵表中。**

**认为这是从部队实体管理的,您必须在其中执行以下事务

1) 将士兵附加到 Troop 实体中的士兵集合

2) 创建士兵。

3) 也更新部队实体。**

因此,这就是为什么在第二个条件下您将进行插入和更新,其中您有 @OneToMany 作为管理方。

现在,回到为什么文档提到 @ManytoOne JoinColumn 应该是 insertable=false, updateable = false 是因为在第二种情况下,(关系的 @OneToMany 端是管理端)您将通过更新 Troop 实体来更新 Soldier。

我认为这与您如何根据您想要管理的关系以及从何处设计应用程序有关。

关于java - 为什么多对一双向关联需要update和insert设置为false,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20958436/

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