tags:

views:

1143

answers:

5

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?

+1  A: 

If you look at the API Set extends Collection. According, to the description the Set does not allow null values.

kazanaki
A: 

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();
Loki
A: 

A Collection is something more general than a Set. A Set is a more specific subinterface of a Collection. See here.

mdm
Link doesn't work.
devoured elysium
+2  A: 

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

Rutesh Makhijani
A: 

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.

Ed Pichler