@OneToMany List<> vs Set<> difference
Asked Answered
Z

2

120

Is there any difference if I use

@OneToMany
public Set<Rating> ratings;

or if I use

@OneToMany
public List<Rating> ratings;

both work OK, i know difference between list and a set, however I don't know if this makes any difference how hibernate (or rather JPA 2.0) handles it.

Zaxis answered 3/7, 2011 at 11:45 Comment(0)
S
132

A list, if there is no index column specified, will just be handled as a bag by Hibernate (no specific ordering).

One notable difference in the handling of Hibernate is that you can't fetch two different lists in a single query. For example, if you have a Person entity having a list of contacts and a list of addresses, you won't be able to use a single query to load persons with all their contacts and all their addresses. The solution in this case is to make two queries (which avoids the cartesian product), or to use a Set instead of a List for at least one of the collections.

It's often hard to use Sets with Hibernate when you have to define equals and hashCode on the entities and don't have an immutable functional key in the entity.

Strophanthin answered 3/7, 2011 at 13:3 Comment(1)
And for the detail of what happens with a list, see https://mcmap.net/q/179996/-hibernate-criteria-returns-children-multiple-times-with-fetchtype-eager/2495717.Gazebo
E
33

If you use a List, then you can specify an 'Order BY' clause in getter function. You can't do that with a Set. The order by clause can contain partial EJBQL; For example

@OneToMany
@OrderBy("lastname ASC")
public List<Rating> ratings;

If you leave this field blank, then the list is sorted in ascending order based on the value of the primary key.

Explanatory answered 3/7, 2011 at 13:9 Comment(3)
Since it sent me scrambling for my Hibernate docs: you can @Sort a set - just use SortedSet as explained in the docs.Psephology
but if you use SortedSet, it sorts with comparator, there is no way to make it ordered by database's "order by".Stein
Since it is old answer, I would like to clarify it. Currently we CAN use @OrderBy on Set. Underneath, Hibernate will use OrderedSetType which will instantiate a LinkedHashSet, so order is preserve. Additionaly I would suggest to use LinkedHashSet in entity - for consistency sake. Source: discourse.hibernate.org/t/…Patsypatt

© 2022 - 2024 — McMap. All rights reserved.