timdisney
timdisney

Reputation: 5347

Difference between Set and Collection in hibernate

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?

Upvotes: 1

Views: 4178

Answers (5)

John John
John John

Reputation: 4575

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.

Upvotes: 0

Rutesh Makhijani
Rutesh Makhijani

Reputation: 17235

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

Upvotes: 3

mdm
mdm

Reputation: 5594

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

Upvotes: 0

Loki
Loki

Reputation: 30960

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();

Upvotes: 0

kazanaki
kazanaki

Reputation: 8054

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

Upvotes: 2

Related Questions