One to many XML mapping in Hibernate

One to many relationship states that a single instance of an entity is associated with multiple instances of the another entity. In other words, each record in one of the tables is associated with multiple records in the other table.

Let us check out how we can define such relationship in Hibernate through XML mapping file.

1. Entity Relationship Diagram

Assuming that we have the student and department tables created in database, below is the Entity Relationship diagram of the student and department tables in the MySQL database.

ER Diagram Student Department

2. Maven Dependency

Let’s first setup the pom.xml file in our maven project.

Make sure we have the following dependencies added to our pom.xml file.

3. Hibernate Configuration setup

Make sure we have the hibernate.cfg.xml file configured and added to the project structure in the classpath.

4. Entity classes

We have two entities involved in our demo application, student and department, for which we have two tables existing in the database. So we need to create entity classes corresponding to these tables.

5. Hibernate Utility class

Create for initial Hibernate configuration which provides us with the SessionFactory isntance.

6. Hibernate mapping XMLs

Create the hibernate mapping file for each of the entities.



Note that we have used Set to map students associated with a department. 

The “Cascade” keyword is often used in the collection mapping to manage the state of the collection automatically. So if there is a set of Students associated with a particular Department and we persist the state of the Department object, all the associated child Student objects also get persisted automatically, thus saving the manual effort to persist them individually. The same is going to happen for our current example.

7. Final Project Structure

Refer to the below project structure once we are done with all the above steps.

One to may project structure

7. Execution

We are almost done. The only part remaining is to create the client class from where we will be executing our application. So let’s create a MainApp client class.

Right click on the class and run it as ‘Java Application’. We see the following entries logged into the IDE console.

Verify the individual tables in the database for added entries.

Department table

Student table

Receive our updates to your inbox

Get more stuff like this
in your inbox

Subscribe to our mailing list and get interesting stuff and updates to your email inbox.