Hibernate one to many mapping example

This is 4 of 8 parts of tutorial series

Tutorial Content:

In this example we will see how to implement one to many relationship using annotations.
Lets take example of Country and state.One Country can have n number of states.Following is relationship diagram among them.

Now to create above tables in database, you need to create two java files i.e. Country.java and State.java.

1.Country.java

Country class will be used to create COUNTRY table in database.
Create Country.java in src->org.arpit.javapostsforlearning.

The @OneToMany annotation is used to create the one-to-many relationship between the Country and State entities. The @JoinTable annotation is used to create the COUNTRY_STATE link table and @JoinColumn annotation is used to refer the linking columns in both the tables.

2.State.java

State class will be used to create STATE table in database.
Create State.java in src->org.arpit.javapostsforlearning.

3.Hiberante.cfg.xml:

Create a file named “hibernate.cfg.xml” in src folder.

4.Main Class:

Project Struture:

5.Run it:

When you run it,you will get following output.

6.SQL output:

COUNTRY table in database

STATE table in database

COUNTRY_STATE table is created to link above two tables.

Source code:

Was this post helpful?

Leave a Reply

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