Welcome to the Hibernate Tutorial Series. In previous tutorial we saw how to implement One to Many Annotation mapping as well as XML mapping. In this tutorial we will understand How to implement Bi-directional Many-to-Many relationship in Hibernate using XML mappings.
First let us see the formal definition of Many-to-Many relationship:
A logical data relationship in which the value of one data element can exist in combination with many values of another data element, and vice versa.
Let us see how to implement Many-to-Many relationship in Hibernate using XML mapping.
1. Create Database
For this example, we will MySQL database. We are using Employee-Meeting relationship as a many to many relationship example. Each Employee can attain more than one meetings and each meetings can have more than one employee
One thing is worth noting here is that we have mentioned keyword inverse=”true” in Meeting class which makes Employee as relationship owner. Thus Employee model takes care of updating referential keys in dependent models.
6. Hibernate Configuration File
Add following hibernate.cfg.xml file in your project.
Note that we have used SET to map meetings with employee and vice versa. A <set> is similar to except that it can only store unique objects. That means no duplicate elements can be contained in a set. When you add the same element to a set for second time, it will replace the old one. A set is unordered by default but we can ask it to be sorted. The corresponding type of a <set> in Java is java.util.Set.
SessionFactory sf = HibernateUtil.getSessionFactory();
Session session = sf.openSession();
Meeting meeting1 = new Meeting("Quaterly Sales meeting");
Meeting meeting2 = new Meeting("Weekly Status meeting");
Employee employee1 = new Employee("Sergey", "Brin");
Employee employee2 = new Employee("Larry", "Page");