JPA @JoinColumn annotation with One To One relationship

无人久伴 提交于 2019-11-29 15:30:46

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.

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.

  • Example:

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

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.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!