Sobes.tech
Senior

How to implement a many-to-many relationship?

sobes.tech AI

Answer from AI

Many-to-many relationships in Java are usually implemented through an intermediate entity (table) or collections within objects.

For example, in JPA/Hibernate, a separate join table is created, and annotations @ManyToMany with @JoinTable are used in entities:

@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, the relationship is implemented through the student_course table, which stores pairs of student_id and course_id. In the code, this is reflected by collections in both entities.