Menu

Many-to-Many Mapping

Many-to-Many Mapping

Join Table

A student can enrol in many courses, and a course has many students. A relational database represents this with a third table, the join table, that stores pairs of keys.

One side owns the relationship and defines the join table with @JoinTable. The other side uses mappedBy.

@Entity
public class Student {
    @Id @GeneratedValue
    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 @GeneratedValue
    private Long id;

    @ManyToMany(mappedBy = "courses")
    private Set<Student> students = new HashSet<>();
}

Code Explanation:

  • student_course is the join table with two foreign key columns.
  • joinColumns points to the owning entity, and inverseJoinColumns points to the other entity.
  • Course is the inverse side, so changes are saved only through Student.courses.
  • A Set is used deliberately. Removing one element from an unordered List can make Hibernate delete every row for that owner and reinsert them.

Avoid CascadeType.REMOVE and CascadeType.ALL here, since deleting one student should not delete courses shared with others. If the link needs its own data, such as an enrolment date, replace the mapping with a separate entity that has two @ManyToOne fields.


Hibernate Tutorial

AP

Abhishek Pati



Learn via Video Course

Java Programming ( Telugu) Logo

Java Programming ( Telugu)

11 hrs



Get in Touch For Details