Hibernate many to many mapping example

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.


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.


Language class will be used to create LANGUAGE table in database.
Create Langauge.java in src->org.arpit.javapostsforlearning.


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:

Related Posts

Leave a Reply

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

Subscribe to our newletter

Get quality tutorials to your inbox. Subscribe now.