Skip to content
Tutorials Center
My learning

Topics

Lesson 18 of 39 ยท Associations and Inheritance

Many-to-Many Mapping

Map many-to-many in Hibernate with @ManyToMany and @JoinTable, choose Set over List, keep both sides in sync, and learn when a link entity with extra columns is better.

A student takes many courses; a course has many students. In SQL this needs a third table, the join table, with one foreign key to each side. Hibernate offers @ManyToMany to hide that table, and a link entity to expose it when it needs its own data.

Real Hibernate code is read-only; the runnable programs are plain-Java stand-ins with real JDBC.

The basic mapping

Java
@Entity
public class Student {
    @Id @GeneratedValue
    private Long id;
    private String name;

    @ManyToMany
    @JoinTable(
        name = "enrollment",
        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;
    private String title;

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

Student is the owning side (it declares @JoinTable); Course is the inverse side (mappedBy). Hibernate writes rows into enrollment(student_id, course_id) only from the owning side, so keep both in sync with helper methods, exactly as in one-to-many:

Java
public void enroll(Course course) {
    courses.add(course);
    course.getStudents().add(this);
}

public void drop(Course course) {
    courses.remove(course);
    course.getStudents().remove(this);
}

Use Set, not List

With a List (a bag), removing one course makes Hibernate delete all the student's rows from the join table and re-insert the rest. A Set has a natural key (the pair of ids), so it deletes exactly one row. For many-to-many, Set is the right default. Remember that Set needs correct equals/hashCode on the entities (identifiers).

Cascade: be careful

A many-to-many partner is a separate, shared entity. Cascading REMOVE from a student to courses would delete courses that other students still use, so never use CascadeType.ALL or REMOVE here. At most use PERSIST and MERGE. See cascade and orphan removal.

Real relationships usually carry attributes: the grade of an enrollment, the date it started. A @ManyToMany has no place for them. Promote the join table to an entity with two many-to-one associations:

Java
@Entity
public class Enrollment {

    @EmbeddedId
    private EnrollmentId id = new EnrollmentId();

    @ManyToOne(fetch = FetchType.LAZY)
    @MapsId("studentId")
    private Student student;

    @ManyToOne(fetch = FetchType.LAZY)
    @MapsId("courseId")
    private Course course;

    private LocalDate enrolledOn;
    private Integer grade;
}

Now Student and Course each have a @OneToMany(mappedBy = ...) list of Enrollments. This is more code, but it is usually the right design as soon as the relationship has its own columns, and it is easier to query (from Enrollment e where e.grade > 80).

Stand-in: the join table

Java Stand-in: join table with a composite key

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Java Stand-in: statements for removing one link

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which collection type is the best default for @ManyToMany?

    A Set has a natural key, so single links can be removed with a single statement.
  2. 2. Which side of a bidirectional @ManyToMany writes to the join table?

    Only the owning side is used to write the join table.
  3. 3. Why avoid CascadeType.REMOVE on @ManyToMany?

    The associated entities are shared and independent.
  4. 4. What should you do when the relationship needs a grade or a date?

    A link entity can hold the extra attributes and be queried directly.

Summary

  • @ManyToMany plus @JoinTable hides the join table; the @JoinTable side is the owning side.
  • Use a Set, keep both sides in sync, and do not cascade REMOVE.
  • When the relationship has its own data, model a link entity with two @ManyToOne and a composite key.
  • Here, real Hibernate code is read-only; the runnable programs are plain-Java stand-ins.

Next: Cascade and Orphan Removal