Collection Mapping in HibernateWe 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:
The persistent class should be defined like this for collection element. Mapping collection in mapping fileThere 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:
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 elementThe 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 collectionsThe collection elements can be categorized in two forms:
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 ElementsThe collection elements can have value or entity reference (another class object). We can use one of the 4 elements
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. Upcoming topics in Collection MappingMapping ListIn this example, we are going to map the List element. Mapping BagIn this example, we are going to use the bag collection of Hibernate framework. Mapping SetHere, we will map the set element of collection. Next TopicMapping List In Collection Mapping |