Hibernate Many to Many XML Mapping

 

In this example, we will see how to map many-to-many relationship in Hibernate using XML configuration.

 

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 two tables : CUSTOMER and ADDRESS

A customer can have one or more addresses, and an address may belongs to one or many customers.

So, we can model this many-to-many relationship between CUSTOMER and ADDRESS as shown below :

Hibernate-Many-to-Many

Tables script :

 

3. Project structure

Hibernate Many to Many XML Mapping

 

4. Model classes

To implement the many-to-many mapping, we add a Set collection of Address objects to the Customer class, and we add a Set collection of Customer objects to the Address class.

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

 

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

 

5. Mapping files

Now, we can create mapping files for each entity Customer and Address.

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

 

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

 

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

 

6. Hibernate configuration file

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

 

7. Hibernate Utility

Build the sessionFactory and get a session instance.

 

8. Test It

We create two customers, Walid and Mariam, they have the same work address, but each one has different home address.

 

Output :

Hibernate: insert into CUSTOMER (TITLE, NAME) values (?, ?)
Hibernate: insert into ADDRESS (STREET, CITY, COUNTRY, TYPE) values (?, ?, ?, ?)
Hibernate: insert into ADDRESS (STREET, CITY, COUNTRY, TYPE) values (?, ?, ?, ?)
Hibernate: insert into CUSTOMER (TITLE, NAME) values (?, ?)
Hibernate: insert into ADDRESS (STREET, CITY, COUNTRY, TYPE) values (?, ?, ?, ?)
Hibernate: insert into CUST_ADDR (CUSTOMER_ID, ADDRESS_ID) values (?, ?)
Hibernate: insert into CUST_ADDR (CUSTOMER_ID, ADDRESS_ID) values (?, ?)
Hibernate: insert into CUST_ADDR (CUSTOMER_ID, ADDRESS_ID) values (?, ?)
Hibernate: insert into CUST_ADDR (CUSTOMER_ID, ADDRESS_ID) values (?, ?)

 

Download source code