Javatpoint Logo
Javatpoint Logo

Hibernate One to Many Example using Annotation

In this section, we will perform one-to-many association to map the list object of persistent class using annotation.

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


One to Many mapping using annotation

In such case, there can be many answers for a question and each answer may have its own information that is why we have used list in the persistent class (containing the reference of Answer class) to represent a collection of answers.

Example of One to Many mapping using annotation

1) Create the Persistent class

This persistent class defines properties of the class including List.

Question.java

Answer.java

2) Add project information and configuration in pom.xml file.

Open pom.xml file and click source. Now, add the below dependencies between <dependencies> .... </dependencies> tag.

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.

Note - Using these annotations in a similar way, we can also perform one-to-many association for set, map and bag objects.

Output

Hibernate One to Many Example using Annotation 1 Hibernate One to Many Example using Annotation 2

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.

Output

Hibernate One to Many Example using Annotation 3





Youtube For Videos Join Our Youtube Channel: Join Now

Feedback


Help Others, Please Share

facebook twitter pinterest

Learn Latest Tutorials


Preparation


Trending Technologies


B.Tech / MCA