Java MCQ: Which JPA annotation is used to define a one-to-many relationship?
Answer:
Explanation:
The @OneToMany
annotation is used to define a one-to-many relationship in JPA. This type of relationship indicates that one instance of an entity is associated with many instances of another entity. The @OneToMany
annotation is typically used on the parent side of the relationship, where the parent entity has a collection of child entities.
Here’s an example:
@Entity
public class Department {
@Id
private Long id;
@OneToMany(mappedBy = "department")
private List<Employee> employees;
private String name;
// Getters and setters
}
In this example, the Department
entity has a one-to-many relationship with the Employee
entity, meaning that a single department can have multiple employees. The mappedBy
attribute in the @OneToMany
annotation indicates that the department
field in the Employee
entity owns the relationship.
One-to-many relationships are common in hierarchical data models and can be easily mapped in JPA using the @OneToMany
annotation.
Reference links:
https://www.rameshfadatare.com/learn-java-programming/
https://www.javaguides.net/p/java-tutorial-learn-java-programming.html