Video in progress

How is a @ManyToMany association stored in the database?

Through an intermediate (join) table that holds the ids of both sides as foreign keys. One side is the owner and names the table with @JoinTable; the other side writes mappedBy.

📖 Answer

Students and courses are the classic example. One student takes many courses, and one course has many students:

@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<>();
}

Choose Set for the collection, not List. With a List, when one element is removed Hibernate may delete all the join rows and re-INSERT the rest.

The biggest limitation in practice: you can't add extra columns to the join table. As soon as you need the date a student enrolled in a course, or a grade, and that happens almost every time, you turn the join table into its own entity (Enrollment) with two @ManyToOnes. That's why many teams take this route from the start.

Don't put CascadeType.REMOVE on a @ManyToMany: if you delete a student, the courses get deleted too, along with the other students' enrollments.