Collection Mapping in Hibernate

We can map collection elements of Persistent class in Hibernate. You 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.


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:

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. But 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:

Now the mapping file will be:

Here, List is mapped by one-to-many relation. In this scenario, there can be many answers for one question.


Understanding key element

The key element is used to define the foreign key in the joined table based on the original identity. The foreign key element is nullable by default. So for non-nullable foreign key, we need to specify not-null attribute such as:

The attributes of the key element are column, on-delete, property-ref, not-null, update and unique.


Indexed collections

The collection elements can be categorized in two forms:

  • indexed ,and
  • non-indexed

The List and Map collection are indexed whereas set and bag collections are non-indexed. Here, indexed collection means List and Map requires an additional element <index>.


Collection Elements

The collection elements can have value or entity reference (another class object). We can use one of the 4 elements

  • element
  • component-element
  • one-to-many, or
  • many-to-many

The element and component-element are used for normal value such as string, int etc. whereas one-to-many and many-to-many are used to map entity reference.