Learn with best explanation

Coding tutorials and solutions

Collection Bag Mapping in Hibernate using XML

When using List<> in our Persistent class then we have option to either use list or bag tag in mapping file for mapping. List is similar to list but it doesn't require index tag.

Observe the code bellow. The first snippet of code showing list mapping for one-to-many relation using list tag in mapping file and second showing same mapping and same relation using bag tag.

List mapping using list tag


<list name="orders" cascade="all"> <!--Collection tag-->
    <key column="customer_frk_id"
         not-null="true"
         on-delete="cascade"
         update="true"
         unique="false"
    />
    <index column="type"></index> <!--necessary index in list tag-->
    <one-to-many class="Orders"/> <!--relation-->
</list>

List mapping using bag tag

Following code doesn't accepet index tag in bag.


<bag name="orders" cascade="all"> <!--Collection tag-->
    <key column="customer_frk_id"
         not-null="true"
         on-delete="cascade"
         update="true"
         unique="false"
    />
    <!--<index column="type"></index>--> <!--doesn't accept index tag-->
    <one-to-many class="Orders"/> <!--relation-->
</bag>