gpt4 book ai didi

java - hibernate/"absolutely necessary with bi-directional links"?

转载 作者:行者123 更新时间:2023-11-29 03:25:17 25 4
gpt4 key购买 nike

这是官方的摘录Hibernate tutorial

First, keep in mind that Hibernate does not affect normal Java semantics. How did we create a link between a Person and an Event in the unidirectional example? You add an instance of Event to the collection of event references, of an instance of Person. If you want to make this link bi-directional, you have to do the same on the other side by adding a Person reference to the collection in an Event. This process of "setting the link on both sides" is absolutely necessary with bi-directional links.

Many developers program defensively and create link management methods to correctly set both sides (for example, in Person):

protected Set getEvents() {
return events;
}

protected void setEvents(Set events) {
this.events = events;
}

public void addToEvent(Event event) {
this.getEvents().add(event);
event.getParticipants().add(this);
}

public void removeFromEvent(Event event) {
this.getEvents().remove(event);
event.getParticipants().remove(this);
}

在这种情况下,“绝对”一词是什么意思? :

  • 这意味着只要当前逻辑过程完成就建议保持关系一致,但持久性显然会发生?
  • 意思是如果不设置另一方(不拥有关系),就不能严格持久化?

换句话说,如果我的“添加”方法是:

public void addToEvent(Event event) {
this.getEvents().add(event);
//event.getParticipants().add(this); without this line
}

最佳答案

A bi-directional关系允许参与关系的两个实体都获得关系另一端的实体。当您插入这些参与双向关系的实体时,您负责管理关系的双方。

在您呈现的参与者/事件关系中,这是通过在关系的两侧设置适当的实体来完成的。

因此,如果您尝试为参与者添加 Activity ,则必须将 Activity 添加到参与者 Collection<Event>并且必须将参与者添加到事件的 Collection<Participant> .您不能简单地将事件添加到参与者的 Collection<Event> 中。并期望 hibernate 填充 Participant在 Activity 的Collection<Participant> .

如果添加失败 ParticipantCollection<Participant>对于一个事件 Collection<Participant>将与数据库不同步,并可能无法插入,具体取决于已建立的约束和级联设置。

关于java - hibernate/"absolutely necessary with bi-directional links"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21369709/

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