Collection Mapping in Hibernate

We can map collection elements of Persistent class in Hibernate. We need to declare the type of collection in Persistent class from one of the following types:

  • java.util.List
  • java.util.Set
  • java.util.SortedSet
  • java.util.Map
  • java.util.SortedMap
  • java.util.Collection
  • or write the implementation of org.hibernate.usertype.UserCollectionType

The persistent class should be defined like this for collection element.


package com.javatportal;

import java.util.List;

public class Question {
private int id;
private String qname;
private List<String> answers;//List can be of any type

//getters and setters

}

Mapping collection in mapping file

There are many subelements of <class> elements to map the collection. They are <list>, <bag>, <set> and <map>. Let's see how we implement the list for the above class:


<class name="com.javatportal.Question" table="q100">
          <id name="id">
          <generator class="increment"></generator>
          </id>
          <property name="qname"></property>
          
          <list name="answers" table="ans100">
          <key column="qid"></key>
          <index column="type"></index>
          <element column="answer" type="string"></element>
          </list>
          
          </class>

There are three subelements used in the list:

  • <key>element is used to define the foreign key in this table based on the Question class identifier.
  • <index>element is used to identify the type. List and Map are indexed collection.
  • <element>is used to define the element of the collection.

This is the mapping of collection if collection stores string objects. In any case, if collection stores entity reference (another class objects),we need to define <one-to-many> or <many-to-many> element. Now the Persistent class will look like:


package com.javatportal;

import java.util.List;

public class Question {
private int id;
private String qname;
private List<Answer> answers;//Here, List stores the objects of Answer class

//getters and setters

}

package com.javatportal;
import java.util.List;
public class Answer {
private int id;
private String answer;
private String posterName;
//getters and setters
}

Now the mapping file will be:

	
<class name="com.javatportal.Question" table="q100">
          <id name="id">
          <generator class="increment"></generator>
          </id>
          <property name="qname"></property>
          
          <list name="answers" >
          <key column="qid"></key>
          <index column="type"></index>
          <one-to-many class="com.javatportal.Answer" />
          </list>
          
          </class>