Mapping Bag in Collection Mapping (using xml file)
If our persistent class has List object, we can map the List by list or bag element in the mapping file. The bag is just like List but it doesn’t require index element.
Here, we are using the scenario of Forum where one question has multiple answers.
Let’s see how we can implement the bag in the mapping file:
Example of mapping bag in collection mapping
In this example, we are going to see full example of collection mapping by bag. This is the example of bag if it stores value not entity reference that is why are going to use element instead of one-to-many. If you have seen the example of mapping list, it is same in all cases instead mapping file where we are using bag instead of list.
1) Create the Persistent class
This persistent class defines properties of the class including List.
2) Create the Mapping file for the persistent class
Here, we have created the question.hbm.xml file for defining the list.
3) Create the configuration file
This file contains information about the database and mapping file.
4) Create the class to store the data
In this class we are storing the data of the question class.
How to fetch the data
Here, we have used HQL to fetch all the records of Question class including answers. In such case, it fetches the data from two tables that are functional dependent.