Video in progress

How does choosing `List`, `Set` or an ordered `List` (`@OrderColumn`) for an entity collection affect Hibernate's behavior?

A List without @OrderColumn is a "bag": duplicates are allowed, order isn't stored, and on a @ManyToMany removing one element often leads to deleting all the join rows and rewriting them. A Set deletes the exact row, and @OrderColumn stores the position in a separate column.

📖 Answer

The difference shows up well with a @ManyToMany:

@ManyToMany
@JoinTable(name = "student_course")
private List<Course> courses = new ArrayList<>();

After student.getCourses().remove(math), Hibernate often does this:

delete from student_course where student_id = ?
insert into student_course (student_id, course_id) values (?, ?)  -- for each remaining one

Because an element in a bag can't be uniquely identified, Hibernate takes the "delete everything and write it again" route. With 3 courses you don't notice; with 300 you do, and triggers and audit logs fire for nothing too.

With Set<Course>:

delete from student_course where student_id = ? and course_id = ?

With @OrderColumn(name = "position") the List becomes an indexed list: the order is stored in the database, but if an element is removed from the middle, the position column of every following row gets UPDATEd.

How I choose:

  • a @ManyToMany or any collection with frequent removals: Set (with correct equals/hashCode);
  • @OneToMany(mappedBy): List is fine too, because deletion touches the child row, not a join table;
  • if a user-defined order matters: @OrderColumn, and for display order @OrderBy("createdAt desc") is enough.

The fact that you can't fetch several bags in one query (MultipleBagFetchException) can also push you toward Set.