Hibernate many to many mapping example

Previous
Next

This is 5 of 8 parts of tutorial series

Tutorial Content:

In this example we will see how to implement many to many relationship using annotations.
Lets take example of Country and Language.One Country can have n number of languages and one language can be spoken by n number of countries.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 Language.java.

1.Country.java

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

The @MamyToMany annotation is used to create the many-to-many relationship between the Country and Language entities. The @JoinTable annotation is used to create the COUNTRY_LANGUAGE link table and @JoinColumn annotation is used to refer the linking columns in both the tables.

2.Langauge.java

Language class will be used to create LANGUAGE table in database.
Create Langauge.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.

5.SQL output:

COUNTRY table in database

LANGUAGE table in database

COUNTRY_LANGUAGE table is created to link above two tables.

Source code:

Previous
Next

Join Our News Letter - Stay Updated

Subscribe to Awesome Java Content.

Add Comment

Join Our News Letter - Stay Updated

Subscribe to Awesome Java Content.
You can like our facebook page Java2blog