Video in progress
Why is Set recommended over List in a @ManyToMany relationship, and what do you do if the join table needs an extra column?
When you remove one element from a List (bag), Hibernate deletes all the rows in the join table and rewrites the rest; with a Set a single DELETE goes out. If the join table needs a column like a date or a grade, instead of @ManyToMany you make a separate entity with two @ManyToOne.
📖 Answer
@Entity
class Student {
@ManyToMany
@JoinTable(name = "student_course",
joinColumns = @JoinColumn(name = "student_id"),
inverseJoinColumns = @JoinColumn(name = "course_id"))
private Set<Course> courses = new HashSet<>();
}
When written with a List (without @OrderColumn), Hibernate treats it as a "bag", a collection with neither order nor uniqueness. If you remove one course from it, here's what you see in the log:
delete from student_course where student_id=? -- all of them
insert into student_course (student_id,course_id) values (?,?) -- the rest again
insert into student_course (student_id,course_id) values (?,?)
For a student with 20 courses, one change means more than 20 queries. With a Set, it's a single precise delete ... where student_id=? and course_id=?.
The condition for Set is that equals/hashCode in Course are written correctly (based on an immutable business key or the id, not on all fields).
One more thing: don't put cascade = CascadeType.REMOVE on @ManyToMany. If a student is deleted, the courses other students are enrolled in get deleted too.
As soon as the join table needs an "enrollment date" or a "grade", @ManyToMany is no longer enough:
@Entity
class Enrollment {
@Id @GeneratedValue Long id;
@ManyToOne(fetch = FetchType.LAZY) Student student;
@ManyToOne(fetch = FetchType.LAZY) Course course;
LocalDate enrolledAt;
Integer grade;
}
In practice I choose this variant from the start in most cases: the business almost always asks for a new column on the join table later, and the migration is more expensive then.
Sign up to mark studied questions and save your progress.