Reputation: 12060
What is the main difference between the Set
and Bag
collections in Hibernate?
In what scenarios should we use Set
and Bag
?
Upvotes: 27
Views: 49085
Reputation: 3503
Quick Summary difference between the various collections is as below
Bag - Can contain Duplicates and No Order (Also called, Unordered List or Set with duplicates)
List - Can contain Duplicates but with Order preserved
Upvotes: 7
Reputation: 8601
A <bag>
is an unordered collection, which can contain duplicated elements. That means if you persist a bag with some order of elements, you cannot expect the same order retains when the collection is retrieved. There is not a “bag” concept in Java collections framework, so we just use a java.util.List
corresponds to a <bag>
.
A <set>
is similar to <bag>
except that it can only store unique objects. That means no duplicate elements can be contained in a set. When you add the same element to a set for second time, it will replace the old one. A set is unordered by default but we can ask it to be sorted. The corresponding type of a in Java is java.util.Set
.
Examples
Mapping <set>
<set name="employees" table="employee"
inverse="true" lazy="true" fetch="select">
<key>
<column name="department_id" not-null="true" />
</key>
<one-to-many class="net.viralpatel.hibernate.Employee" />
</set>
Mapping <bag>
<bag name="employees" table="employee"
inverse="true" lazy="true" fetch="select">
<key>
<column name="employee_id" not-null="true" />
</key>
<one-to-many class="net.viralpatel.hibernate.Employee" />
</bag>
Thus, both are mapped exactly same way in hbm file. But differs only in the way it handles duplicate records.
Source: Hibernate One to Many XML Tutorial
Upvotes: 28
Reputation: 12541
From the Hibernate reference:
Bags are the worst case since they permit duplicate element values and, as they have no index column, no primary key can be defined. Hibernate has no way of distinguishing between duplicate rows.
And also:
There is a particular case, however, in which bags, and also lists, are much more performant than sets. For a collection with
inverse="true"
, the standard bidirectional one-to-many relationship idiom, for example, we can add elements to a bag or list without needing to initialize (fetch) the bag elements.
Upvotes: 8
Reputation: 245479
Both are unordered collections. Bags allow duplicates. Sets do not.
Upvotes: 2