Java MCQ: Which annotation is used to define a one-to-one relationship in JPA?
Answer:
Explanation:
The @OneToOne
annotation is used to define a one-to-one relationship in JPA. This type of relationship indicates that one instance of an entity is associated with exactly one instance of another entity. The @OneToOne
annotation is used on both sides of the relationship, with one side typically owning the relationship (using @JoinColumn
) and the other side mapped to it.
Here’s an example:
@Entity
public class Employee {
@Id
private Long id;
@OneToOne
@JoinColumn(name = "address_id")
private Address address;
private String name;
// Getters and setters
}
In this example, the Employee
entity has a one-to-one relationship with the Address
entity, meaning that each employee has a unique address. The @JoinColumn
annotation specifies the foreign key column that references the Address
entity.
One-to-one relationships are used in cases where each entity has a unique counterpart, and they are easily represented in JPA using the @OneToOne
annotation.
Reference links:
https://www.rameshfadatare.com/learn-java-programming/
https://www.javaguides.net/p/java-tutorial-learn-java-programming.html