Junior — Middle
How can a many-to-many relationship be implemented in a database or ORM?
sobes.tech AI
Answer from AI
A many-to-many relationship in a database is implemented through an intermediate table (join table), which contains foreign keys to both related tables. For example, if there are tables Students and Courses, a Student_Course table is created with fields student_id and course_id.
In ORM, such as in Java using JPA/Hibernate, this can be implemented with the @ManyToMany annotation and specifying the join table with @JoinTable.
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 Set<Course> courses = new HashSet<>();
}
@Entity
public class Course {
@Id
private Long id;
@ManyToMany(mappedBy = "courses")
private Set<Student> students = new HashSet<>();
}
Thus, ORM automatically manages the many-to-many relationship through the intermediate table.