Unidirectional One-To-Many Relationship with Join Tables 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. The one side of the association will implement one of the collection interfaces, if it has the reference to the other entity.

In one to many relationship, multiple target objects can have relationship with same source object. Let’s consider CD and Artist. So many Artists can write only one CD. So we will create three tables CD, Artist and CDArtist in the database and we will see how one-to-many relationship works step by step.

A unidirectional one-to-many association on a join table is to specify unique=”true” which changes the multiplicity from many-to-many to one-to-many.

Step 1. Create tables

Create table – CD

 

Create table – Artist

 

Create table – CDArtist

 

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.

hibernate.reveng.xml

 

hibernate.cfg.xml

 

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

Artist.hbm.xml

 

Step 6. Create mapping xml file and POJO for cd table. Look at the xml file, we have <many-to-many /> with unique=”true” which makes sure one-to-many relationship.

Cd.hbm.xml

 

Step 7. Now we will create a main class for testing unidirectional one-to-many with join tables.

 

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

inserted data into artist table

 

inserted data into cd table

 

inserted data into cdartist table

 

Console Output

 

That’s all. Thanks for your reading.

Soumitra

Software Professional, I am passionate to work on web/enterprise application. For more information please go to about me. You can follow on Twitter. You can be a friend on Facebook or Google Plus or Linkedin

Leave a Reply

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

Time limit is exhausted. Please reload CAPTCHA.