gpt4 book ai didi

hibernate - 关系所有者在双向关系中意味着什么?

转载 作者:行者123 更新时间:2023-12-02 19:32:56 25 4
gpt4 key购买 nike

我有一个带有 QuestionChoice 对象的简单模型。

  • 一个问题有多种选择。
  • 多种选择都有一个问题

有两种方法可以使用 Hibernate 来实现这一点

实现一:业主方选择

问题.java

@OneToMany (mappedBy="question")
private Set choices = new HashSet();

选择.java

@ManyToOne
@JoinColumn (name="QUESTION_ID")
private Question question;

实现二:业主方提出问题

问题.java

@OneToMany
@JoinColumn (name = "QUESTION_ID")
private Set choices = new HashSet();

选择.java

@ManyToOne
@JoinColumn (name="QUESTION_ID", updatable = false, insertable = false)
private Question question;

这两种实现有什么区别?

最佳答案

您的第一个示例是正常且正确的双向一对多/多对一映射。将 Question 设置为 Choice 属性(“拥有方”)足以维持关系。内存中的实体图将变得困惑,直到再次从数据库读取关系的另一端。来自数据库观点所有者是持久保存到具有外键列的表的实体(双向一对一相同)。在规范中,这是这样解释的:

The many side of one-to-many / many-to-one bidirectional relationships must be the owning side, hence the mappedBy element cannot be specified on the ManyToOne annotation.
....
Bidirectional relationships between managed entities will be persisted based on references held by the owning side of the relationship. It is the developer’s responsibility to keep the in-memory references held on the owning side and those held on the inverse side consistent with each other when they change. In the case of unidirectional one-to-one and one-to-many relationships, it is the developer’s responsibility to insure that the semantics of the relationships are adhered to.

在 JPA 术语中,您的第二个示例没有拥有方,因为缺少 mappedBy。相反,您有两个单向关系,它们被迫使用同一列作为存储。至少在 Hibernate 3.5.6 中,它的行为如下:

  • 问题设置为选择属性不会持久关系。
  • Choice 添加到 question 属性不会持久关系。
  • 要将值保留到“QUESTION_ID”,两者都必须设置(是的,也是不可插入 问题)。

关于hibernate - 关系所有者在双向关系中意味着什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8931342/

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