What is the difference between using a Set or a Collection for @OneToMany or @ManyToMany properties on my hibernate entity objects?
Does Hibernate map things differently depending on which one you choose?
What is the difference between using a Set or a Collection for @OneToMany or @ManyToMany properties on my hibernate entity objects?
Does Hibernate map things differently depending on which one you choose?
Collection is an Interface, cannot be instantiated. Set is also an Interface.
As such, it doesn't matter what you use, as long as the instantiated object that you use is compatible with those.
So normally, you would do something like this:
private Set parts = new HashSet();
A Collection is something more general than a Set. A Set is a more specific subinterface of a Collection. See here.
In the context of hibernate, following is the scenario under which you would use Set instead of Collection: -
"From Order as orders left fetch join orders.orderLineItems as orderLineItems ORDER BY orders.id DESC"
It returns duplicates so use the hash set to remove them.
Query query = session.getNamedQuery("OrdersAndLoadLineItems");
Set set = new LinkedHashSet();
set.addAll(query.list());
return set;
This is taken from Hibernate FAQ link is http://www.hibernate.org/117.241.html
I don't know the difference, but if you use Set you can fetch multiple bags in JPA, but if you use List, for instance, you cannot fetch multiple bags in a query.