@OneToOne in JPA: Definition, Example, and Usage Guide
@OneToOne in JPA defines a direct one-to-one relationship between two entities, meaning each instance of one entity is linked to exactly one instance of another. It is used to map such exclusive pairs in the database with foreign keys.How It Works
Imagine you have two people who each have exactly one passport. The @OneToOne annotation in JPA models this kind of exclusive pairing between two entities. It tells the database that for every record in one table, there is exactly one matching record in another table.
Behind the scenes, JPA uses foreign keys to link these two tables. One entity holds a reference to the other, and the database enforces that this link is unique and exclusive. This is different from one-to-many or many-to-many relationships where multiple records can be linked.
This setup helps keep data organized when two pieces of information belong tightly together but are stored separately for clarity or design reasons.
Example
This example shows two entities: Person and Passport. Each person has exactly one passport, and each passport belongs to exactly one person.
import jakarta.persistence.Entity; import jakarta.persistence.Id; import jakarta.persistence.OneToOne; import jakarta.persistence.JoinColumn; @Entity public class Person { @Id private Long id; private String name; @OneToOne @JoinColumn(name = "passport_id") private Passport passport; // getters and setters } @Entity public class Passport { @Id private Long id; private String number; // getters and setters }
When to Use
Use @OneToOne when two entities have a strict one-to-one relationship, like a user and their profile, or a car and its registration document. It is ideal when you want to split data into separate tables but keep a direct exclusive link.
For example, if you store sensitive information separately for security or performance reasons, @OneToOne helps keep the connection clear and enforce uniqueness.
Key Points
@OneToOnemaps a single entity instance to exactly one instance of another entity.- It uses foreign keys to enforce this exclusive link in the database.
- Often combined with
@JoinColumnto specify the foreign key column. - Useful for splitting related data into separate tables without losing the one-to-one connection.
- Can be unidirectional or bidirectional depending on whether both entities reference each other.
Key Takeaways
@OneToOne defines a strict one-to-one link between two entities in JPA.@JoinColumn to specify the linking column.