A one-to-one (1:1) relationship means that one entity is associated with exactly one other entity.
For example:
Approach |
Description |
---|---|
Using |
Uses a foreign key in one table. |
Using |
Uses a bidirectional relationship. |
Using |
Uses shared primary keys. |
@JoinColumn
:
User
has One Profile
id
, name
, and a reference to profile_id
.id
and bio
.Table name : profiles
id | bio |
---|---|
1 | Java Developer |
Table name : users
id | name | profile_id |
---|---|---|
1 | John Doe | 1 |
mappedBy
(Bidirectional):Profile
entity owns the relationship (foreign key is in User
).mappedBy="profile"
tells Hibernate that Profile
is responsible.Table name : users
id | name |
---|---|
1 | John Doe |
Table name : profiles
id | bio | user_id |
---|---|---|
1 | Java Developer | 1 |
@PrimaryKeyJoinColumn
(Shared Primary Key):User
and Profile
share the same primary key.Table name : users
id | name |
---|---|
1 | John Doe |
Table name : profiles
id | bio |
---|---|
1 | Java Developer |
In this guide, we will implement CRUD (Create, Read, Update, Delete) operations for a One-to-One Mapping using Hibernate.
Output