Java.Hibernate.Beginner.What is one-to-one mapping in Hibernate?

A one-to-one mapping in Hibernate represents a relationship where one entity instance is associated with exactly one instance of another entity, and vice versa. It models a real-world scenario where two tables have a one-to-one relationship (e.g., UserUserProfile).


🔹 Example scenario:
A User entity has exactly one UserProfile entity containing extra details like address, phone, etc.


🔹 How to map one-to-one in Hibernate:
Use JPA annotations @OneToOne along with @JoinColumn (for unidirectional) or mappedBy (for bidirectional) relationships.

@Entity
public class User {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String username;

    @OneToOne
    @JoinColumn(name = "profile_id") // foreign key in 'users' table
    private UserProfile profile;
}

@Entity
public class UserProfile {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String address;
}

🔹 Here:

  • The users table has a foreign key column profile_id referencing user_profile.id.
  • You can fetch the profile of a user with user.getProfile().

Bidirectional one-to-one example:

@Entity
public class User {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @OneToOne(mappedBy = "user")
    private UserProfile profile;
}

@Entity
public class UserProfile {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @OneToOne
    @JoinColumn(name = "user_id") // foreign key in 'user_profile' table
    private User user;
}

🔹 Here:

  • Both entities can reference each other.
  • mappedBy on User points to UserProfile.user → establishes ownership on UserProfile.

🔹 Fetch type:
By default, @OneToOne uses FetchType.EAGER, meaning the related entity is loaded automatically with the owning entity. You can switch to LAZY if needed:

@OneToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "profile_id")
private UserProfile profile;

🔹 Key points about one-to-one mapping:
✅ Models exclusive relationships → one row on one side corresponds to exactly one row on the other.
✅ Requires a unique foreign key constraint in the database for true one-to-one enforcement.
✅ Can be unidirectional (one entity references the other) or bidirectional (both reference each other).

Key takeaway:
One-to-one mapping in Hibernate models exclusive relationships between two entities and maps them via @OneToOne, typically using foreign keys with unique constraints to enforce the relationship.

This entry was posted in Без рубрики. Bookmark the permalink.

Leave a Reply

Your email address will not be published.