How do you define a one-to-one relationship in JPA?
A) By using the @OneToOne annotation
B) By using the @OneToMany annotation
C) By using the @ManyToOne annotation
D) By using the @ManyToMany annotation
Answer:
A) By using the @OneToOne annotation
Explanation:
The @OneToOne
annotation in JPA is used to define a one-to-one relationship between two entities. In a one-to-one relationship, each instance of one entity is associated with exactly one instance of another entity. This relationship can be unidirectional or bidirectional, depending on how you want to navigate between the entities.
For example:
@Entity
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
@OneToOne
@JoinColumn(name = "address_id")
private Address address;
// Getters and setters
}
In this example, the User
entity has a one-to-one relationship with the Address
entity. The @JoinColumn
annotation is used to specify the foreign key column in the User
table that refers to the primary key of the Address
entity.
One-to-one relationships are useful for modeling scenarios where two entities are closely related, and each entity has a unique counterpart, such as a user and their address.