Difference between Set and Bag in Hibernate

hibernate

Solution

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

Problem

What is the main difference between the `Set` and `Bag` collections in Hibernate? In what scenarios should we use `Set` and `Bag`?

Original source