Hibernate Many to Many Annotation

 

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

We will use the Hibernate Many to Many XML Mapping  example and adjust it to support annotations.

 

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

Hibernate-Many-to-Many

Tables script :

 

3. Project structure

Hibernate Many to Many Annotation

 

4. Model classes

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

@ManyToMany is used to define the many-to-many association between Customer and Address.

@JoinTable is used to describe the join table : CUST_ADDR

Since we are using a bidirectional many-to-many relationship, the CUSTOMER table is the owner of the relationship and the ADDRESS table is the inverse end.

@JoinColumn is used to define the CUSTOMER_ID column as a foreign key to the CUSTOMER table, and the ADDRESS_ID column as a foreign key to the ADDRESS table.

 

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

We have added  the @ManyToMany mapping with the mappedBy argument on the customers property to indicate that this is the owner side of the relationship.

 

5. Hibernate configuration file

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

 

6. Hibernate Utility

Build the sessionFactory and get a session instance.

 

7. Test It

We create two customers, Walid and Mariam, they have the same work address, but each one has a 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