Hibernate One to Many XML Mapping Example

 

In this tutorial, we will see how to perform one to many mapping in Hibernate using XML mapping files.

 

1. Technologies used

  • Hibernate 4.3.6.Final
  • MySQL 5.1
  • Maven 3.0.5
  • Eclipse 4.4
  • JDK 1.7

 

2. Create tables

We will use CUSTOMER and ORDERS tables.

Each customer have one or more orders, and an order belongs only to one customer.

So, there will be a one-to-many relationship between CUSTOMER and ORDERS tables:

Hibernate-One-to-Many-XML-Mapping-1

In ORDERS table, CUSTOMER_ID is foreign key that references the primary key column in CUSTOMER table.

Tables script :

 

3. Project structure

We create a Maven based Java application.

Hibernate-One-to-Many-XML-Mapping

 

4. Project dependencies

 

5. Model classes

We will create our model classes to persist the objects associated to CUSTOMER and ORDERS tables.

To implement the one-to-many mapping, we will use :
– In Customer class, a Set collection of Orders objects.
– In Orders class, a property to reference the Customer entity.

File : src/main/java/com/keylesson/persistence/Customer.java

 

File : src/main/java/com/keylesson/persistence/Orders.java

 

6. Mapping files

Now, we will create mapping files to map our two classes to the database tables.

File : src/main/resources/com/keylesson/persistence/Customer.hbm.xml

 

The Set collection is mapped with a <set../> element.

We have used the one-to-many element to create an association from Orders class to the Customer class.

 

File : src/main/resources/com/keylesson/persistence/Orders.hbm.xml

 

By using one-to-many on Customer entity and many-to-one on Orders entity, we tell Hibernate that Customer is the parent object and Orders is the child object.

 

7. Hibernate configuration file

File : src/main/resources/hibernate.cfg.xml

 

8. Hibernate Utility

Build the sessionFactory and get a session instance.

 

9. Test It

We create a customer that have two orders.

 

Output :

Hibernate: insert into CUSTOMER (TITLE, NAME) values (?, ?)
Hibernate: insert into CUSTOMER_DETAIL (ADDRESS, TEL, CREATION_DATE, CUSTOMER_ID) values (?, ?, ?, ?)

 

Download source code