Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

@OneToMany List<> vs Set<> difference

Tags:

java

jpa

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.

like image 475
M4ks Avatar asked Jul 03 '11 11:07

M4ks


People also ask

Why we use Set instead of List in java?

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.

Is set more efficient than list Java?

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.

What is difference between list and bag in Hibernate?

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.

What is the difference between @ElementCollection and @OneToMany?

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.


1 Answers

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.

like image 175
JB Nizet Avatar answered Oct 16 '22 02:10

JB Nizet