The example you have provided is the one to one bidirectional relationship.
Bidirectional relationship means that both the entities will store reference of each other in the domain model. But,
It does not mean both of the tables will be storing reference to one another as well. The relationship is still unidirectional at the database level.
In bidirectional relationship there are:
1. Owning side
2. Referencing side.
So, what is the owning side?
Let's understand this referring to your first example.
(I have added @JoinColumn
and Table
annotations to make things clearer for beginners).
@Entity
@Table(name="a")
class A {
@Id int id;
@OneToOne
@JoinColumn(name="b_id")
B b;
}
@Entity
@Table(name= "b")
class B {
@Id int id;
@OneToOne(mappedBy="b")
A a;
}
Here, let assume, the corresponding tables for entities A
and B
are a
and b
respectively.
We have used @JoinColumn
in entity A
and set its value as b_id
. It means that a column named b_id
will be created in table a
which will store the id
or reference of the table b
. This column, b_id
, also acts as a foreign key. Note that, although a bidirectional relationship,
table b is not storing the reference to table a.
Since, table a
is storing the relationship information i.e. reference to table b
, its corresponding entity, A
, is called the owner entity.
And, the other entity,B
, is called the referencing entity. It references the owner entity, A
, using mappedBy
attribute.
Similarly, in the second example, B
is the owning entity and A
is the reference entity.