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.

1.Country.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.
@joinColumn
is used to specify a mapped column for joining an entity association.

2.Capital.java

Capital class will be used to create CAPITAL table in database.
Create Capital.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.SQL output:

COUNTRY table in database

CAPITAL table in database

Source code:

Was this post helpful?

Leave a Reply

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