Unidirectional One-To-One Relationship on Primary Key in Hibernate

In unidirectional association, we will have navigation only in one direction, i.e, only one side of the association will have the reference to the other side.

In one to one relationship, one source object can have relationship with only one target object. Let’s consider CD and Artist. So one CD can be written by one Artist or an Artist can write only one CD. So we will create two tables CD and Artist in the database and we will see how one-to-one relationship works step by step.

Now we will apply one-to-one relationship. So only one CD can be written by only one Artist.

In One-To-One relationship on primary key CD table and Artist table have cdId as primary keys, where primary key cdId in Artist table is a reference to CD table.

Step 1. Create tables

Create table – cd


Create table – artist


Step 2. Create a java project in any Java based IDE and configure for hibernate jars.

Step 3. Create hibernate reverse engineering and configuration file.


Step 4. Create hibernate utility class which creates singleton SessionFactory from which Session object will be created.


Step 5. Create mapping xml file and POJO for artist table. Look at the xml file, we have <one-to-one /> with constraint constrained=”true” which makes sure that one-to-one relationship on primary key and only one CD can be written by one Artist.


Step 6. Create mapping xml file and POJO for cd table.


Step 7. Now we will create a main class for testing one-to-one on primary key.


Step 8. Run the main class and see the output as shown below. While we save value for artist, the below values are stored into the database tables.

inserted data into artist table


inserted data into cd table




That’s all. Thanks for your reading.

Leave a Reply

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

Time limit is exhausted. Please reload CAPTCHA.