2

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?

3
  • Can you use collection? I thought collection is the generic term but you have to decide between Bag, Set, SortedSet, etc. .. Commented Feb 2, 2009 at 18:44
  • Looking at the answers and the direction I was thinking .. where are you using the set or the collection .. in the mapping xml or in your java code to retrieve the results of a query? Commented Feb 2, 2009 at 18:59
  • I'm using hibernate annotations so I'll have @OneToMany private Set<Foo> foo; or @OneToMany private Collection<Foo> foo; Both seem to work but I'm trying to understand what if any difference there is. Commented Feb 2, 2009 at 19:06

5 Answers 5

3

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

Sign up to request clarification or add additional context in comments.

Comments

2

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

Comments

0

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

Comments

0

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

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.