🔹 Bidirectional relationship
A bidirectional relationship means both entities know about each other in your Java model:
- You can navigate the relationship from either side in your code.
- Both entities have fields referencing each other.
- Example:
User
has aUserProfile
field, andUserProfile
has aUser
field.
This makes it easy to traverse in both directions:
user.getProfile();
profile.getUser();
🔹 Unidirectional relationship
A unidirectional relationship means only one entity knows about the other:
- Only one side has a field referencing the other entity.
- You can navigate only in one direction in your code.
- Example:
User
hasUserProfile
, butUserProfile
has no reference back toUser
.
This limits navigation:
user.getProfile(); // works
profile.getUser(); // not possible → no user field
🔹 Practical example:
✅ Unidirectional
@Entity
public class User {
@OneToOne
@JoinColumn(name = "profile_id")
private UserProfile profile; // User → UserProfile only
}
✅ Bidirectional
@Entity
public class User {
@OneToOne(mappedBy = "user")
private UserProfile profile;
}
@Entity
public class UserProfile {
@OneToOne
@JoinColumn(name = "user_id")
private User user; // UserProfile → User
}
🔹 Database schema
🚫 There’s no difference in the physical database: whether you use unidirectional or bidirectional mapping, you still have a foreign key enforcing the relationship.
🔹 Key differences summarized:
Aspect | Unidirectional | Bidirectional |
---|---|---|
Navigation | One side only (A → B) | Both sides (A ↔ B) |
Java mapping | One entity has a reference | Both entities have references |
Use case | Simpler, less code | Needed when you must navigate both ways |
✅ Key takeaway:
- Unidirectional → simpler, but can navigate only one way.
- Bidirectional → more flexible; you can navigate the relationship from either entity → recommended when both sides need to interact or need business logic involving both.