具有一对一关系的JPA @JoinColumn批注 [英] JPA @JoinColumn annotation with One To One relationship

查看:78
本文介绍了具有一对一关系的JPA @JoinColumn批注的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

@JoinColumn是否可以在JPA的一对一关系的两边使用?我印象深刻的是,它应该总是用于一对一关系的拥有一方,因为拥有一方将有外键列,该注释定义了外键列的属性.请说明我的理解是否正确.

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 .

编辑#1 -我想知道,在哪种情况下,我们将在一对一关系的两边都使用@JoinColumn批注?

Edit #1 - I wanted to know , In which scenario we will be using @JoinColumn annotation on both side of one to one relationship ?

推荐答案

OneToOne关系不一定是双向的. 当在源对象和目标对象中都存在对该关系的另一个对象的引用时,就会发生双向OneToOne关系.

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关系中,在关系的拥有方使用单个外键.另一方面,目标实体必须使用 mappedBy 属性.

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 mappedBy attribute.

  • 示例:

让我们考虑一下 Player Website 对象之间的OneToOne关系.

Let's consider a OneToOne relationship between a Player and a Website objects.

每个播放器实体仅对应一个网站实体:

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;
  ...
}

如果我们将"mappedBy"选项添加到网站"实体,则OneToOne单向关联将转换为双向关联:

If we add the mappedBy option to the Website entity, the OneToOne unidirectional association will be transfornmed into a bidirectional one:

@Entity
public class Website {
  @Id
  @Column(name = "WEBSITE_ID")
  private long id;
  ...
  @OneToOne(mappedBy="website")
  private Player websiteOwner;
  ...
}

您可以查阅此链接和此

You can consult this link and this one for more information.

这篇关于具有一对一关系的JPA @JoinColumn批注的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆