Hibernate one to many mapping annotation example

In this example, You will learn about Hibernate one to many mapping annotation example. We will use MySQL database and Maven build tool.

According to the relationship, a Branch can have any number of Student. To create this relationship you need to have a Student and Branch table. 

Hibernate one to many mapping annotation example Relational model:

"<yoastmark

 

Hibernate Model Class:

File: Branch.java

File: Student.java

Important annotation:

  • @OneToMany: This annotation is used to create the one-to-many relationship between the entities.
  • @JoinColumn: This annotation is used to refer to the linking columns in both the tables.

Configuration File:

Now create the hibernate configuration file with the Branch and Student class mapping.

 

File: HibernateUtil.java

Create a java util class for creating the sessionfactory object.

Run the application:

Hibernate will insert a row into the branch table and a row into the student table.

Output:

Project Structure:

Hibernate one to many mapping annotation example
Hibernate one to many mapping annotation example

Leave a Reply

Your email address will not be published. Required fields are marked *

Show Buttons
Hide Buttons