java 具有一对一关系的 JPA @JoinColumn 注释
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/38054178/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
JPA @JoinColumn annotation with One To One relationship
提问by RaJ
Is it true that @JoinColumn can be used on both side of One to One relationship in JPA ? I was under impression that it should be always used in owning side of One to One relationship as owning side will have foreign key column and this annotation define the attribute of foreign key column . Please clarify if my understanding is not correct .
@JoinColumn 真的可以用于 JPA 中一对一关系的双方吗?我的印象是它应该始终用于一对一关系的拥有方,因为拥有方将具有外键列,并且此注释定义了外键列的属性。如果我的理解不正确,请澄清。
Edit #1- I wanted to know , In which scenario we will be using @JoinColumn annotation on both side of one to one relationship ?
编辑 #1- 我想知道,在哪种情况下我们将在一对一关系的两侧使用 @JoinColumn 注释?
回答by Strider
The OneToOne relationship is not necessarily bi-directional. A bi-directional OneToOne relationship happens when a reference exists to the other object of the relationship in both the source and the target objects.
OneToOne 关系不一定是双向的。当在源对象和目标对象中都存在对关系的另一个对象的引用时,就会发生双向 OneToOne 关系。
In a bi-directional OneToOne relationship, a single foreign key is used in the owning side of the relationship. On the other hand, the target entity must use the mappedByattribute.
在双向 OneToOne 关系中,关系的拥有方使用单个外键。另一方面,目标实体必须使用mappedBy属性。
- Example:
- 例子:
Let's consider a OneToOne relationship between a Playerand a Websiteobjects.
让我们考虑Player和Website对象之间的 OneToOne 关系。
Each player entity corresponds to exactly one website entity:
每个玩家实体对应一个网站实体:
@Entity
public class Player {
@Id
@Column(name="PLAYER_ID")
private long id;
...
@OneToOne
@JoinColumn(name="WEBSITE_ID")
private Website website;
...
}
If we add the mappedBy option to the Website entity, the OneToOne unidirectional association will be transfornmed into a bidirectional one:
如果我们给网站实体添加了mappedBy 选项,OneToOne 单向关联将被转换为双向关联:
@Entity
public class Website {
@Id
@Column(name = "WEBSITE_ID")
private long id;
...
@OneToOne(mappedBy="website")
private Player websiteOwner;
...
}