10

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 .

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

RaJ
  • 151
  • 2
  • 4
  • 11

1 Answers1

10

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.

Strider
  • 3,539
  • 5
  • 32
  • 60
  • thanks . so my question is - In which scenario we will be using @JoinColumn annotation on both side of one to one relationship ? – RaJ Jun 29 '16 at 14:56
  • 2
    The @JoinColumn annotation is used only on the owning side of the relationship: Whether the relationship is bidirectional or unidirectional, it doesn't change how the tables are associated...When you decide to use the OneToOne relationship as bidirectional, you allow navigation in both directions...You can refer to [this answer](http://stackoverflow.com/a/9421078/5486116) that discusses your very question – Strider Jun 29 '16 at 18:40