Java.Hibernate.Beginner.Explain what means bidirectional ? What’s difference to unidirectional ?

🔹 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 a UserProfile field, and UserProfile has a User 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 has UserProfile, but UserProfile has no reference back to User.

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:

AspectUnidirectionalBidirectional
NavigationOne side only (A → B)Both sides (A ↔ B)
Java mappingOne entity has a referenceBoth entities have references
Use caseSimpler, less codeNeeded 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.
This entry was posted in Без рубрики. Bookmark the permalink.

Leave a Reply

Your email address will not be published.