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.
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.
hibernate.cfg.xml
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd"> <hibernate-configuration> <session-factory> <property name="hibernate.hbm2ddl.auto">create</property> <property name="hibernate.show_sql">true</property> <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property> <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property> <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/hibernateannotation</property> <property name="hibernate.connection.username">root</property> <property name="hibernate.connection.password">root</property> <mapping class="com.javainfinite.pojo.Employee"/> <mapping class="com.javainfinite.pojo.Address"/> </session-factory> </hibernate-configuration>
NewHibernateUtil.java
package com.javainfinite.pojo; import org.hibernate.cfg.AnnotationConfiguration; import org.hibernate.SessionFactory; /** * Hibernate Utility class with a convenient method to get Session Factory * object. * * @author Vikram */ public class NewHibernateUtil { private static final SessionFactory sessionFactory; static { try { // Create the SessionFactory from standard (hibernate.cfg.xml) // config file. sessionFactory = new AnnotationConfiguration().configure().buildSessionFactory(); } catch (Throwable ex) { // Log the exception. System.err.println("Initial SessionFactory creation failed." + ex); throw new ExceptionInInitializerError(ex); } } public static SessionFactory getSessionFactory() { return sessionFactory; } }
Address.java
package com.javainfinite.pojo; import java.io.Serializable; import java.util.ArrayList; import java.util.List; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.ManyToMany; import javax.persistence.Table; @Entity @Table(name="Address_Mapping") public class Address implements Serializable { @Id @GeneratedValue private int address1; private String city; @Column(name="State_EMP") private String state; @ManyToMany private List<Employee> employee=new ArrayList(); public List<Employee> getEmployee() { return employee; } public void setEmployee(List<Employee> employee) { this.employee = employee; } public int getAddress1() { return address1; } public void setAddress1(int address1) { this.address1 = address1; } public String getCity() { return city; } public void setCity(String city) { this.city = city; } public String getState() { return state; } public void setState(String state) { this.state = state; } }
Employee.java
package com.javainfinite.pojo; import java.util.ArrayList; import java.util.List; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.ManyToMany; import javax.persistence.Table; @Entity @Table(name="Employee_Mapping") public class Employee { @Id @GeneratedValue @Column(name="Employee_ID") private int eid; @Column(name="Employee_Name") private String ename; @Column(name="Employee_Dept") private String edept; @ManyToMany private List<Address> address=new ArrayList(); public List<Address> getAddress() { return address; } public void setAddress(List<Address> address) { this.address = address; } public int getEid() { return eid; } public void setEid(int eid) { this.eid = eid; } public String getEname() { return ename; } public void setEname(String ename) { this.ename = ename; } public String getEdept() { return edept; } public void setEdept(String edept) { this.edept = edept; } }
Execution.java
package com.javainfinite.execution; import com.javainfinite.pojo.Address; import com.javainfinite.pojo.Employee; import com.javainfinite.pojo.NewHibernateUtil; import org.hibernate.Session; import org.hibernate.Transaction; public class Execution { public static void main(String args[]) { Session session=NewHibernateUtil.getSessionFactory().openSession(); Transaction trans=session.beginTransaction(); Employee emp=new Employee(); Employee emp1=new Employee(); Address addr=new Address(); Address addr1=new Address(); emp.setEname("Alpha"); emp.setEdept("Robotics"); emp.getAddress().add(addr); emp.getAddress().add(addr1); emp1.setEname("Beta"); emp1.setEdept("Computers"); addr.setCity("New York City"); addr.setState("New York"); addr.getEmployee().add(emp); addr.getEmployee().add(emp1); addr1.setCity("San Francisco"); addr1.setState("California"); session.save(emp); session.save(emp1); session.save(addr); session.save(addr1); trans.commit(); } }
From the output,
Employee_Mapping table saves both the employee records
Address_Mapping table saves both the addresses
Employee_Mapping_Address_Mapping has the employee ID mapped to the corresponding address
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