What does the @OneToMany annotation represent in JPA?
A) A relationship where one entity is associated with many entities
B) A relationship where many entities are associated with one entity
C) A relationship where one entity is associated with one other entity
D) A relationship where many entities are associated with many entities
Answer:
A) A relationship where one entity is associated with many entities
Explanation:
The @OneToMany
annotation in JPA is used to define a relationship where one entity is associated with many entities. This annotation is commonly used to represent relationships like “one department has many employees” or “one customer has many orders.”
For example:
@Entity
public class Department {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
@OneToMany(mappedBy = "department")
private List<Employee> employees;
// Getters and setters
}
In this example, the Department
entity has a @OneToMany
relationship with the Employee
entity, meaning that one department can have many employees. The mappedBy
attribute is used to specify the field in the Employee
entity that owns the relationship.
The @OneToMany
annotation is essential for modeling complex relationships between entities in a relational database, ensuring that the associations are correctly mapped and managed by JPA.