Hibernate Many to Many Relations Set Or List?

From relational databases perspective this is a set. Databases do not preserve order and using a List is meaningless, the order in them is unspecified (unless using so called indexed collections).

Using a Set also has great performance implications. When List is used, Hibernate uses PersistentBag collection underneath which has some terrible characteristics. I.e.: if you add a new relationship it will first delete all existing ones and then insert them back + your new one. With Set it just inserts the new record.

Third thing – you cannot have multiple Lists in one entity as you will get infamous cannot simultaneously fetch multiple bags exception.

See also:

  • 19.5. Understanding Collection performance

  • Why Hibernate does “delete all then re-insert” – its not so strange

Leave a Comment