Javatpoint Logo

91-9990449935

 0120-4256464

One to Many mapping in Hibernate by List Example (using xml file)

If the persistent class has list object that contains the entity reference, we need to use one-to-many association to map the list element. We can map this list object by either list or bag.

Notice that bag is not index-based whereas list is index-based.

Here, we are using the scenario of Forum where one question has multiple answers.

Mapping Bag in hibernate

Let's see the persistent class that has list objects. In this case, there can be many answers for a question and each answer may have its own informations that is why we have used list element (containing Answer objects) to represent a collection of answers.

The Answer class has its own informations such as id, answername, postedBy etc.

The Question class has list object that have entity reference (i.e. Answer class object). In such case, we need to use one-to-many of bag to map this object. Let's see how we can map it.


Example of mapping bag in collection mapping by one to many association

In this example, we are going to see full example of mapping list that contains entity reference.

1) create the Persistent class

This persistent class defines properties of the class including List.

Question.java

Answer.java


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 of List

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. Here, we are direct printing the object of answer class, but we have overridden the toString() method in the Answer class returning answername and poster name. So it prints the answer name and postername rather than reference id.

FetchData.java


OUTPUT

mapping bag by one to many