Hibernate one to one mapping example


This is 3 of 8 parts of tutorial series

Tutorial Content:

In this example, we will see how to implement one to one relationship using annotations.

Lets take example of Country and Capital.One Country has one capital.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 Capital.java.


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

@OneToOne annotation is used to create one to one relationship between Country and Capital entities.
is used to specify a mapped column for joining an entity association.


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


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

4.Main Class:

Project Struture:

5.SQL output:

COUNTRY table in database

CAPITAL table in database

Source code:


Add Comment