ManyToMany Mapping in Hibernate using Annotations

ManyToMany Mapping in Hibernate using Annotations
In our previous examples we have seen OneToOne and OneToMany mappings. In this article let us see how to implement ManyToMany annotation in Hibernate using Annotations.

Let us understand how ManyToMany mapping works. For example, let us consider 2 entities – Employee and Address. An employee can have more than one address let us assume permanent and temporary address, Same way more than one employee would have stayed in the temporary address. This scenario shows Employee can have more than one address and an address can have more than one employee. This is ManyToMany mapping.

screen1

This is a simple example, From the diagram we can understand that an employee 1 has more than one address associated with him, same way temporary address has more than one employee associated with it. This is known as ManyToMany mapping.

Now let us see an example.

Structure
Structure

hibernate.cfg.xml

NewHibernateUtil.java

Address.java

Employee.java

Execution.java

Output:
op1

From the output,
Employee_Mapping table saves both the employee records

op4

Address_Mapping table saves both the addresses

op5

Employee_Mapping_Address_Mapping has the employee ID mapped to the corresponding address
op2
we can see that employee with id: 1 is mapped with address ID 1 and 2

 Address_Mapping_Employee_Mapping
Same way here the address 1 is mapped to both Employee’s with ID 1 and 2
op3

 

 

 

Leave a Reply

Your email address will not be published. Required fields are marked *