gpt4 book ai didi

jpa - @OneToOne 是否意味着唯一性?

转载 作者:行者123 更新时间:2023-12-05 01:46:38 29 4
gpt4 key购买 nike

我只用@OneToOne 注释我的字段,当我检查数据库(使用 liquibase 生成)时发现数据库列有唯一约束。

这是否意味着@OneToOne 本身就意味着唯一性,例如。一栋建筑只能在一个城市,其他建筑不能在同一个城市吗?

当我想告诉同一个城市可能还有其他建筑物时,我该怎么办?

  • 添加@JoinColumn(unique = false),
  • 只使用@JoinColumn(unique = false),不使用@oneToOne,
  • 或使用@ManyToOne?
  • 还是不加任何注释?

我不想在城市类中放置 Buildings 字段,因为我永远不会调用 city.getBuildings();。以下是否需要双向引用?

class Building {
@OneToOne(optional = false)
City city;
}

class Building {
@OneToOne(optional = false)
@JoinColumn(unique = false)
City city;
}

class Building {
@JoinColumn(unique = true)
City city;
}

class Building {
@ManyToOne
City city;
}

最佳答案

JPA specification表示对于双向一对一关系(2.10.1 双向一对一关系):

Assuming that:

  • Entity A references a single instance of Entity B.
  • Entity B references a single instance of Entity A.
  • Entity A is specified as the owner of the relationship.

The following mapping defaults apply:

  • Entity A is mapped to a table named A.
  • Entity B is mapped to a table named B.
  • Table A contains a foreign key to table B. [...] The foreign key column has the same type as the primary key of table B and there is a unique key constraint on it.

在单向一对一关系的情况下(2.10.3.1 单向一对一关系):

The following mapping defaults apply:

  • Entity A is mapped to a table named A.
  • Entity B is mapped to a table named B.
  • Table A contains a foreign key to table B. [...] The foreign key column has the same type as the primary key of table B and there is a unique key constraint on it.

如果您有城市-建筑关系,那么对于任何合理的城市来说,这将是一对多/多对一关系,因为一个给定的城市可以有多个建筑,但一个给定的建筑只能在一个城市中。

关于jpa - @OneToOne 是否意味着唯一性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34789247/

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