Hibernate One to Many Example using XML
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.
Here, we are using the scenario of Forum where one question has multiple answers.
In such case, there can be many answers for a question and each answer may have its own informations that is why we have used list in the persistent class (containing the reference of Answer class) to represent a collection of answers.
Let’s see the persistent class that has list objects (containing Answer class objects).
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 list to map this object. Let’s see how we can map it.
Full example of One to Many mapping in Hibernate by List
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.
OUTPUT
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