What is the main difference between the Set and Bag collections in Hibernate?
In what scenarios should we use Set and Bag?
What is the main difference between the Set and Bag collections in Hibernate? In
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
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 ajava.util.Listcorresponds 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 isjava.util.Set.Examples
Mapping
<set>Mapping
<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