Bidirectional Many-To-One/One-To-Many Relationship in Hibernate

In bidirectional association, we will have navigations in both direction, i.e, both side of the association will have the reference to the other side. The both side of the association will implement one of the collection interfaces, if it has the reference to the other entity.

In many-to-one/one-to-many relationship, multiple source objects can have relationship with same target object or same target object will have multiple source objects and from both direction the navigation is possible. Let’s consider CD and Artist. So multiple CDs can be written by same Artist or same Artist can have multiple CDs. So we will create two tables CD and Artist in the database and we will see how many-to-one/one-to-many relationship work step by step.

Now we will apply many-to-one/one-to-many relationship. So multiple CDs can be written by same Artist or the same Artist can have multiple CDs.

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

 

Step 6. Create mapping xml file and POJO for cd table. Look at the xml file, we have <many-to-one /> which makes sure that multiple CDs can be written by same Artist.

 

Step 7. Now we will create a main class for testing many-to-one/one-to-many.

many-to-one testing

 

one-to-many testing

 

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

many-to-one

inserted data into artist table

 

inserted data into cd table

 

Console output

 

one-to-many

inserted data into artist table

 

inserted data into cd table

 

Console output

 

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.