Senior
How to implement a one-to-one relationship in a database?
sobes.tech AI
Answer from AI
A one-to-one relationship in a database is implemented using a foreign key with a unique constraint.
Example:
There are two tables: User and UserProfile. Each user has exactly one profile.
CREATE TABLE User (
id SERIAL PRIMARY KEY,
username VARCHAR(50) NOT NULL
);
CREATE TABLE UserProfile (
id SERIAL PRIMARY KEY,
user_id INT UNIQUE REFERENCES User(id),
bio TEXT
);
Here, user_id in UserProfile is a foreign key to User.id with a UNIQUE constraint, ensuring that each user has at most one profile.
In Java, using JPA/Hibernate, this can be described as:
@Entity
public class User {
@Id
private Long id;
@OneToOne(mappedBy = "user", cascade = CascadeType.ALL)
private UserProfile profile;
}
@Entity
public class UserProfile {
@Id
private Long id;
@OneToOne
@JoinColumn(name = "user_id", unique = true)
private User user;
}
Thus, the one-to-one relationship is enforced at the database and ORM level.