Java MCQ: Which annotation is used to define a many-to-one relationship in JPA?
Answer:
Explanation:
The @ManyToOne
annotation is used to define a many-to-one relationship in JPA. This type of relationship means that many instances of an entity can be associated with one instance of another entity. The @ManyToOne
annotation is typically used in the entity that holds the foreign key in the relationship.
Here’s an example:
@Entity
public class Employee {
@Id
private Long id;
@ManyToOne
@JoinColumn(name = "department_id")
private Department department;
private String name;
// Getters and setters
}
In this example, the Employee
entity has a many-to-one relationship with the Department
entity, meaning that multiple employees can belong to the same department. The foreign key column is specified using the @JoinColumn
annotation.
Many-to-one relationships are common in database schemas and are easily represented in JPA using the @ManyToOne
annotation.
Reference links:
https://www.rameshfadatare.com/learn-java-programming/
https://www.javaguides.net/p/java-tutorial-learn-java-programming.html