Scrivio Interview library
ConceptFoundations5 min read · updated 12 November 2026

Why is a Set usually preferred over a List for a @ManyToMany association in Hibernate, and when should you replace @ManyToMany with an explicit join entity?

A List without an order column is mapped as a bag, a collection Hibernate cannot address row by row, so removing one element can make it delete every link row for the owner and re-insert the rest. A Set gives each link row a unique identity, so Hibernate deletes only the one removed link. We replace @ManyToMany with an explicit join entity, such as Enrollment between Student and Course, as soon as the link needs its own data like a date or role, and we never cascade REMOVE across a many-to-many, because it would delete entities shared with others.

Why this question is asked

Many-to-many relationships are everywhere: students and courses, posts and tags, users and roles. JPA makes them look trivial with one annotation, and the collection type we pick looks like a style choice. It is not: it decides how many SQL statements a small change produces, and the wrong cascade can delete data other records depend on. Interviewers ask this to see whether we understand what Hibernate does with the link table. In this answer, we will recap how @ManyToMany is stored, compare List and Set on a removal, introduce a join entity when the link carries data, and see why cascading remove is dangerous.

1A Quick Recap: The Link Table

A many-to-many relationship needs a link table, also called a join table, in the database: student_course(student_id, course_id). Each row says one student takes one course. With @ManyToMany, JPA hides that table: Student has a collection of Course, and Hibernate inserts and deletes link rows as we add and remove courses.

The link rows have no id of their own. Hibernate identifies a row only by the values in it, the pair of foreign keys. Whether it can use that pair to target one row depends on the collection type, which is where List and Set differ.

2Removing One Course With a List

With a java.util.List and no @OrderColumn, Hibernate maps the collection as a bag: unordered, duplicates allowed. Because duplicates are allowed, a pair such as (1, 30) is not guaranteed to identify a single row, so Hibernate cannot safely delete just that one. It rewrites the whole collection instead.

Java
@ManyToMany
@JoinTable(name = "student_course",
joinColumns = @JoinColumn(name = "student_id"),
inverseJoinColumns = @JoinColumn(name = "course_id"))
private List<Course> courses = new ArrayList<>();
student.getCourses().remove(math); // the student had 6 courses
// delete from student_course where student_id = 1
// insert into student_course (student_id, course_id) values (1, 10)
// insert into student_course (student_id, course_id) values (1, 11)
// ... 5 inserts in total

For six courses this is a curiosity. For a post with 50 tags, every removal becomes 1 delete and 49 inserts, more lock traffic and more work for replication, and briefly the post has no tags at all within the transaction.

3The Same Removal With a Set

A Set promises no duplicates, so each (student_id, course_id) pair is unique, and Hibernate can delete exactly that row.

Java
@ManyToMany
@JoinTable(name = "student_course", ...)
private Set<Course> courses = new HashSet<>();
student.getCourses().remove(math);
// delete from student_course where student_id = 1 and course_id = 30
List versus Set for @ManyToMany
AspectList (bag)Set
Remove one elementdelete all links, re-insert restdelete one link row
Duplicatesallowednot allowed
Needs equals/hashCodenot for removalyes, stable across persist
Join fetch with another bagMultipleBagFetchExceptionallowed (but Cartesian rows)
For many-to-many, Set matches the meaning of the link table.

The change is one word in Java and turns many statements into one. It does require a correct equals() and hashCode() on Course, because a HashSet finds elements by them. A natural key such as a unique course code is ideal; an id-based equals must cope with a null id before persist, typically with a constant hashCode per class. The database should also have a primary key on (student_id, course_id), which enforces the same no-duplicates rule.

4When the Link Needs Its Own Data: A Join Entity

Soon someone asks: when did the student enrol, and with what role, such as auditor or credit student? A @ManyToMany cannot hold that, because the link table is hidden. The answer is to make the link a first-class entity, Enrollment, with two @ManyToOne associations and its own fields. The many-to-many becomes two one-to-many relationships.

Java
@Entity
public class Enrollment {
@Id @GeneratedValue private Long id;
@ManyToOne(fetch = FetchType.LAZY) private Student student;
@ManyToOne(fetch = FetchType.LAZY) private Course course;
private LocalDate enrolledOn;
@Enumerated(EnumType.STRING) private Role role;
}
// unique constraint on (student_id, course_id) keeps one enrollment per pair
enrollmentRepository.save(new Enrollment(student, course, LocalDate.now(), Role.CREDIT));
enrollmentRepository.deleteByStudentAndCourse(student, math); // one targeted delete

A join entity also solves the removal problem by construction, since every row has its own id, and it gives us a natural place for queries such as all enrollments this term. Many teams start with the join entity whenever they suspect the link will grow, because converting a @ManyToMany later means a data migration.

5Never Cascade REMOVE Across Many-to-Many

With cascade = CascadeType.REMOVE (or ALL) on Student.courses, deleting a student would delete each of their courses, the Course rows themselves, not just the links. Those courses are shared with hundreds of other students, so we would either delete data other students depend on or hit foreign key errors halfway through. Removing a student should only remove that student's link rows, which Hibernate does automatically for the owning side of a @ManyToMany. Cascading PERSIST or MERGE can be acceptable when we create both sides together, but REMOVE never is.

6Follow-up questions

Which side of a @ManyToMany owns the link table?

The side without mappedBy. Only changes to the owning collection are written to the link table, so in a bidirectional many-to-many we still need helper methods that update both collections, just as with one-to-many.

Does @OrderColumn fix the List problem?

It gives Hibernate a position column so it can address rows by index, which avoids the full rewrite in some cases. But removing from the middle shifts indexes, causing updates to later rows, and the order is rarely meaningful for a many-to-many. A Set is usually simpler.

Can we fetch many-to-many collections efficiently for a list of posts?

Yes, with a JOIN FETCH or entity graph on one collection per query, or @BatchSize on the collection so Hibernate loads tags for many posts in a few IN queries. Avoid loading them lazily one post at a time.

7Conclusion

In this answer, we saw why Set is preferred for @ManyToMany. A List without an order column is a bag, so Hibernate cannot target one link row and rewrites the whole collection on a removal, while a Set lets it delete exactly one row, provided equals and hashCode are stable. When the link has its own data, such as an enrolment date or role, we replace @ManyToMany with a join entity like Enrollment. And we never cascade REMOVE across a many-to-many, because it would delete entities that other records share.

What to say in the interviewAbout 80 seconds aloud

Open with

The reason is how Hibernate handles the link table. If I map a @ManyToMany as a List without an order column, Hibernate treats it as a bag, which allows duplicates, so a pair of foreign keys doesn't identify a single link row.

Then, if they want more

When I remove one element, it deletes all the link rows for that owner and re-inserts the remaining ones, so removing one tag from a post with 50 tags is one delete and 49 inserts. With a Set, each pair is unique, so Hibernate issues one delete for exactly that row.

The catch is that the element needs a stable equals and hashCode, ideally on a natural key, or an id-based one that handles a null id before persist, and the link table should have a composite primary key.

I'd replace @ManyToMany with an explicit join entity as soon as the link has data of its own, for example an Enrollment between Student and Course with an enrolment date and a role. That gives each link its own id, a natural place for queries, and avoids a migration later.

And I'd never cascade REMOVE on a many-to-many, because deleting a student would delete the shared courses themselves, not just the links.

About this answer

Last updated
12 November 2026
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "Why is a Set usually preferred over a List for a @ManyToMany association in Hibernate...": https://scrivio-interview-library.netlify.app/databases/jpa-relationships/7066779fc2/