Sunday, December 8, 2013

What is the main difference between the Set and Bag collections in Hibernate? In what scenarios should we use Set and Bag?
share|improve this question
1 
Read the documentation of List and Set interfaces. –  AVD Dec 11 '12 at 1:37
add comment

3 Answers

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.
share|improve this answer
add comment
 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 ajava.util.List corresponds to a .
 is similar to  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 
  name="employees" table="employee"
            inverse="true" lazy="true" fetch="select">
        
             name="department_id" not-null="true" />
        
class="net.viralpatel.hibernate.Employee" />
Mapping 
   name="employees" table="employee"
                inverse="true" lazy="true" fetch="select">
            
                 name="employee_id" not-null="true" />
            
class="net.viralpatel.hibernate.Employee" />
Thus, both are mapped exactly same way in hbm file. But differs only in the way it handles duplicate records.
share|improve this answer
add comment
Both are unordered collections. Bags allow duplicates. Sets do not.
share|improve this answer

No comments: