Skip to content
Tutorials Center
My learning

Topics

Lesson 17 of 39 ยท Associations and Inheritance

One-to-One Mapping

Map one-to-one associations in Hibernate: a foreign key with @JoinColumn, the bidirectional mappedBy side, the lazy-loading catch, and the shared primary key with @MapsId.

A one-to-one association links exactly one row to at most one other: a user and their profile, a passport and its holder. It looks simple, but it has two traps: the inverse side cannot be lazy as easily as you would hope, and there are two ways to model the key. This lesson shows both models and what each costs.

Real Hibernate code is read-only; the runnable programs are plain-Java stand-ins with real JDBC.

Foreign key one-to-one

Java
@Entity
public class UserAccount {
    @Id @GeneratedValue
    private Long id;
    private String email;

    @OneToOne(fetch = FetchType.LAZY, cascade = CascadeType.ALL, orphanRemoval = true)
    @JoinColumn(name = "profile_id", unique = true)
    private Profile profile;
}

@Entity
public class Profile {
    @Id @GeneratedValue
    private Long id;
    private String bio;
}

user_account.profile_id is a unique foreign key. Unique makes it one-to-one instead of many-to-one. The side with @JoinColumn is the owning side.

Bidirectional with mappedBy

Java
@Entity
public class Profile {
    @Id @GeneratedValue
    private Long id;

    @OneToOne(mappedBy = "profile", fetch = FetchType.LAZY)
    private UserAccount owner;
}

Here is the catch. When Hibernate loads a Profile, it must know whether owner is null or an object. Because the foreign key is in the other table, only a query can tell, so Hibernate loads the owner immediately, and LAZY is effectively ignored on the mappedBy side. If you do not need the inverse direction, leave it out. If you do, expect that extra select, or use the shared primary key below.

Shared primary key with @MapsId

The cleanest one-to-one makes the child's primary key equal the parent's. There is no extra column and no separate id generator:

Java
@Entity
public class Profile {

    @Id                                   // no @GeneratedValue: the id is copied from the owner
    private Long id;

    @OneToOne(fetch = FetchType.LAZY)
    @MapsId
    @JoinColumn(name = "id")
    private UserAccount owner;

    private String bio;
}

@MapsId tells Hibernate to use the owner's id as this entity's primary key. profile.id is both primary key and foreign key to user_account.id. Loading a profile by user id is then a primary key lookup: session.find(Profile.class, user.getId()). This also solves the lazy problem on the other side if you drop the inverse mapping and fetch the profile by id when needed.

When to split into two tables at all

A one-to-one is usually not necessary. Two reasons to use it:

  • Large or rarely used columns (a long biography, an image) that you do not want in every query of the main table.
  • Optional data that exists only for some rows.

Otherwise put the fields in one table, and group them with an embeddable in Java if the grouping helps.

Stand-in: shared primary key in SQL

Java Stand-in: child PK = parent PK

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Stand-in: why the inverse side cannot be lazy

Java Stand-in: null or object?

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What makes a foreign key one-to-one rather than many-to-one?

    Uniqueness ensures at most one referring row per target.
  2. 2. Why is LAZY ineffective on the mappedBy side of a one-to-one?

    The foreign key is in the other table, so the existence of the associated row is unknown without a query.
  3. 3. What does @MapsId do?

    The primary key doubles as the foreign key to the owner.
  4. 4. When is a separate table for a one-to-one worthwhile?

    Otherwise keep the columns in one table and group them with an embeddable.

Summary

  • A one-to-one is a unique foreign key; the side with @JoinColumn owns it.
  • The mappedBy side cannot be lazily loaded without extra tricks; omit it if you can.
  • @MapsId gives a shared primary key, the leanest model.
  • Use a separate table only for big, rare or optional data.
  • Here, real Hibernate code is read-only; the runnable programs are plain-Java stand-ins.

Next: Many-to-Many Mapping