Java MCQ: Which JPA annotation is used to define a many-to-many relationship?
Answer:
Explanation:
The @ManyToMany
annotation is used to define a many-to-many relationship in JPA. This type of relationship means that multiple instances of one entity can be associated with multiple instances of another entity. The @ManyToMany
annotation is typically used on both sides of the relationship, with a join table used to manage the associations.
Here’s an example:
@Entity
public class Student {
@Id
private Long id;
@ManyToMany
@JoinTable(name = "student_course",
joinColumns = @JoinColumn(name = "student_id"),
inverseJoinColumns = @JoinColumn(name = "course_id"))
private List<Course> courses;
private String name;
// Getters and setters
}
In this example, the Student
entity has a many-to-many relationship with the Course
entity, meaning that a student can be enrolled in multiple courses, and a course can have multiple students. The @JoinTable
annotation specifies the join table that manages this relationship.
Many-to-many relationships are common in relational databases, and they are easily represented in JPA using the @ManyToMany
annotation.
Reference links:
https://www.rameshfadatare.com/learn-java-programming/
https://www.javaguides.net/p/java-tutorial-learn-java-programming.html