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.
The main difference between List and Set is that List allows duplicates while Set doesn't allow duplicates. List is an ordered collection it maintains the insertion order, which means upon displaying the list content it will display the elements in the same order in which they got inserted into the list.
List allows duplicates while Set doesn't allow duplicate elements . All the elements of a Set should be unique if you try to insert the duplicate element in Set it would replace the existing value. List permits any number of null values in its collection while Set permits only one null value in its collection.
Hibernate's naming of the different collection types is a little bit confusing because Lists and Bags are both mapped by a java. util. List. The difference between them is that a List is ordered and a Bag is unordered.
I believe @ElementCollection is mainly for mapping non-entities (embeddable or basic) while @OneToMany is used to map entities. So which one to use depend on what you want to achieve.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With