What is the main difference between the Set
and Bag
collections in Hibernate? In what scenarios should we use Set
and Bag
?
We have seen that sets are unordered collections of items, which do not contain duplicates. A sequence is an ordered collection of items, that may contain duplicates. A bag is an unordered collection of items that may contain duplicates.
Hibernate's naming of the different collection types is a little bit confusing because Lists and Bags are both mapped by a java. util. List. The difference between them is that a List is ordered and a Bag is unordered.
Hibernate in Practice - The Complete Course A Bag is a java collection that stores elements without caring about the sequencing, but allow duplicate elements in the list. A bag is a random grouping of the objects in the list. A Collection is mapped with a <bag> element in the mapping table and initialized with java.
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With