Hibernate Many-To-Many Mapping Example – XML Mapping

In this Hibernate Many-To-Many Mapping Example, we will learn how Hibernate Many-To-Many relationship works. Let’s take the Example of Employee and Department, one Employee can be part of many Departments and similarly one Department can have many Employees. Let’s dig into the code.

In Many-to-Many relationship a mediator table is mandatory, this table stores the primary key of both tables (EMPLOYEE and DEPARTMENT) as a foreign key.

Creating table

Create EMPLOYEE, DEPARTMENT and EMPLOYEE_DEPARTMENT Tables, simply Copy and Paste the following SQL query in the query editor to get the table created.

 CREATE TABLE "EMPLOYEE" 
 ( 
 "EMP_ID" NUMBER(10,0) NOT NULL ENABLE, 
 "EMP_NAME" VARCHAR2(255 CHAR), 
  PRIMARY KEY ("EMP_ID")
 );
 
 CREATE TABLE "DEPARTMENT" 
 ( 
 "DEP_ID" NUMBER(10,0) NOT NULL ENABLE, 
 "DEP_NAME" VARCHAR2(255 CHAR), 
  PRIMARY KEY ("DEP_ID")
 );
 
 CREATE TABLE "EMPLOYEE_DEPARTMENT" 
 ( 
 "EMP_ID" NUMBER(10,0) NOT NULL ENABLE, 
 "DEP_ID" NUMBER(10,0) NOT NULL ENABLE, 
  PRIMARY KEY (EMP_ID , DEP_ID),
  CONSTRAINT FK_EMP_ID FOREIGN KEY (EMP_ID) REFERENCES EMPLOYEE (EMP_ID),
  CONSTRAINT FK_DEP_ID FOREIGN KEY (DEP_ID) REFERENCES DEPARTMENT (DEP_ID)
 );

Folder Structure:

Hibernate Many-To-Many Mapping

  1. Create a simple Maven Project “HibernateTutorial” and create a package for our source files com.javainterviewpointunder  src/main/java 
  2. Now add the following dependency in the POM.xml
     <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
     xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
       <modelVersion>4.0.0</modelVersion>
       <groupId>HibernateTutorial</groupId>
       <artifactId>HibernateTutorial</artifactId>
       <version>0.0.1-SNAPSHOT</version>
       <properties>
          <hibernate.version>4.3.11.Final</hibernate.version>
          <oracle.connector.version>11.2.0</oracle.connector.version>
       </properties>
    
       <dependencies>
         <!-- Hibernate -->
         <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-core</artifactId>
            <version>${hibernate.version}</version>
         </dependency>
    
         <!-- Oracle -->
         <dependency>
            <groupId>com.oracle</groupId>
            <artifactId>ojdbc14</artifactId>
            <version>${oracle.connector.version}</version>
         </dependency>
       </dependencies>
       <build>
         <sourceDirectory>src</sourceDirectory>
         <plugins>
           <plugin>
             <artifactId>maven-compiler-plugin</artifactId>
             <version>3.3</version>
             <configuration>
             <source>1.7</source>
             <target>1.7</target>
             </configuration>
           </plugin>
         </plugins>
       </build>
     </project>
  3. Create the Java classes Employee.java, Department.java, HibernateManyToMany.java   and RetrieveData.java under  com.javainterviewpoint folder.
  4. Place the employee.hbm.xml, department.hbm.xml, hibernate.cfg.xml under the src/main/resources  directory

Hibernate Many-To-Many Mapping Example

Employee.java

Create a new Java file Employee.java under the package com.javainterviewpoint and add the following code

package com.javainterviewpoint;

import java.util.Set;

public class Employee
{
    private int empId;
    private String empName;
    
    private Set department;
    
    
    public Employee()
    {
        super();
    }
    public Employee(String empName)
    {
        super();
        this.empName = empName;
    }
    public int getEmpId()
    {
        return empId;
    }
    public void setEmpId(int empId)
    {
        this.empId = empId;
    }
    public String getEmpName()
    {
        return empName;
    }
    public void setEmpName(String empName)
    {
        this.empName = empName;
    }
    
    public Set getDepartment()
    {
        return department;
    }
    public void setDepartment(Set department)
    {
        this.department = department;
    }
    @Override
    public String toString()
    {
        return "Employee [empId=" + empId + ", empName=" + empName + "]";
    }
}

Our Employee class is a simple POJO class consisting of the getters and setters for the Employee class properties (empId, empName,department). We have a Set of department to hold the Department objects.

Department.java

Create a new Java file Department.java under the package com.javainterviewpoint and add the following code

package com.javainterviewpoint;

import java.util.Set;

public class Department
{
    private int depId;
    private String depName;
    
    private Set employee;

    public Department()
    {
        super();
    }

    public Department(String depName)
    {
        super();
        this.depName = depName;
    }

    public int getDepId()
    {
        return depId;
    }

    public void setDepId(int depId)
    {
        this.depId = depId;
    }

    public String getDepName()
    {
        return depName;
    }

    public void setDepName(String depName)
    {
        this.depName = depName;
    }

    public Set getEmployee()
    {
        return employee;
    }

    public void setEmployee(Set employee)
    {
        this.employee = employee;
    }

    public Department(int depId, String depName, Set employee)
    {
        super();
        this.depId = depId;
        this.depName = depName;
        this.employee = employee;
    }
}

employee.hbm.xml

Place the employee.hbm.xml file under the src/main/resources folder

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
 <hibernate-mapping package="com.javainterviewpoint">
   <class name="Employee" table="EMPLOYEE">
     <id name="empId" column="EMP_ID" type="java.lang.Integer">
       <generator class="native"></generator>
     </id>
     <property name="empName" column="EMP_NAME"></property>
     <set name="department" table="EMPLOYEE_DEPARTMENT" cascade="all" >
      <key column="EMP_ID"></key>
      <many-to-many column="DEP_ID" class="Department"></many-to-many>
     </set>
   </class>
</hibernate-mapping>
  • The “employee.hbm.xml” tells hibernate to map “Employee.class” with the “EMPLOYEE” table in the database.
  • Next tag is the <id> tag, this tag tells which column needs to be marked as primary key in the database table, here our id property of the Employee class is the primary key. We have selected the generator as native, it takes the sequence in Oracle if no sequence name is provided then HIBERNATE_SEQUENCE” will be used
  • The property empName are mapped with EMP_NAME column in the table.
  • We need to specify the property “department” to point the table “EMPLOYEE_DEPARTMENT” and many-to-many tag maps to the class Department.

department.hbm.xml

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
  <hibernate-mapping package="com.javainterviewpoint">
   <class name="Department" table="DEPARTMENT">
    <id name="depId" column="DEP_ID" type="java.lang.Integer">
     <generator class="native"></generator>
    </id>
    <property name="depName" column="DEP_NAME"></property>
    <set name="employee" table="EMPLOYEE_DEPARTMENT" inverse="true" >
     <key column="DEP_ID"></key>
     <many-to-many column="EMP_ID" class="Employee"></many-to-many>
    </set>
   </class>
 </hibernate-mapping>
  • The “department.hbm.xml” tells hibernate to map “Department.class” with the “DEPARTMENT” table in the database.
  • For the <id> tag we have selected the generator as native, so it takes the sequence in Oracle. Here our dep_id field act as a primary key.
  • The property depName are mapped with DEP_NAME column in the table.
  • For the Set “employee” we have set the inverse=”true” so that Employee class will act as the relationship owner.

hibernate.cfg.xml

Place the hibernate.cfg.xml file also under the src/main/resources folder

 <?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
 "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
 "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">

<hibernate-configuration>

 <session-factory>

 <!-- Database connection settings -->
 <property name="hibernate.connection.driver_class">oracle.jdbc.driver.OracleDriver</property>
 <property name="hibernate.connection.username">root</property>
 <property name="hibernate.connection.password">root</property>
 <property name="hibernate.connection.url">jdbc:oracle:thin:@mydb:40051:dev</property>

 <!-- JDBC connection pool (use the built-in) -->
 <property name="connection.pool_size">1</property>

 <!-- SQL dialect -->
 <property name="hibernate.dialect">org.hibernate.dialect.Oracle10gDialect</property>

 <!-- Echo all executed SQL to stdout -->
 <property name="show_sql">true</property>

 <!-- Drop and re-create the database schema on startup -->
 <property name="hibernate.hbm2ddl.auto">update</property>

 <!-- Mapping resource file -->
 <mapping resource="employee.hbm.xml" />
 <mapping resource="departement.hbm.xml" />
</session-factory> 
</hibernate-configuration>
  • First and foremost property is for specifying the JDBC Driver class, in my case it OracleDriver
<property name="hibernate.connection.driver_class">oracle.jdbc.driver.OracleDriver</property>
  • Give the connection URL for connecting the database and provide username and password for connecting the above database
<property name="hibernate.connection.url">jdbc:oracle:thin:@mydb:40051:dev</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password">root</property>
  • Specify the connection pool size, this property limits the number of connections in the Hibernate connection pool.
<property name="connection.pool_size">1</property>
  • Dialect Property makes the Hibernate generate the SQL for the corresponding database which is being used. In this example we are using Oracle database hence Oracle query will be generated. If you are using MySQL database then you need to change the dialect accordingly.
<property name="hibernate.dialect">org.hibernate.dialect.Oracle10gDialect</property>
  • The show_sql property will print the executed sql in the console when set to true.
<property name="show_sql">true</property>
  • If the property “hibernate.hbm2ddl.auto” is set to “create”  This will drop and recreate the database schema on every execution. If it is set to “update” then the database schema will be updated every time rather than dropping and recreating.
<property name="hibernate.hbm2ddl.auto">update</property>
  • Under the Mapping resource tag  we need to specify all the mapping file for which we need the table to be created or updated.
<mapping resource="employee.hbm.xml" />
<mapping resource="department.hbm.xml" />

Hibernate Many-To-Many Example

package com.javainterviewpoint;

import java.util.HashSet;
import java.util.Set;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;

public class HibernateManyToMany
{
    public static void main(String args[])
    {
        //Reading the hibernate configuration file
        Configuration configuration = new Configuration().configure("hibernate.cfg.xml");
        StandardServiceRegistryBuilder regBuilber = new StandardServiceRegistryBuilder();
        regBuilber.applySettings(configuration.getProperties());
        ServiceRegistry serviceRegistry = regBuilber.build();
        
        //Create SessionFacctory
        SessionFactory sessionFactory = configuration.buildSessionFactory(serviceRegistry);
        
        //Create Session from SessionFactory
        Session session = sessionFactory.openSession();
        
        //Begin the transaction
        session.beginTransaction();
        
        //Create a two Employee Objects
        Employee employee1 = new Employee();
        employee1.setEmpName("Employee 1");
        
        Employee employee2 = new Employee();
        employee2.setEmpName("Employee 2");

        //Create two Department Objects
        Department department1 = new Department();
        department1 .setDepName("Mechanical Department");
        
        Department department2 = new Department();
        department2 .setDepName("Electrical Department");
        
        Set s = new HashSet();
        s.add(department1);
        s.add(department2);
        
        //Set Department into Employee
        employee1.setDepartment(s);
        employee2.setDepartment(s);
        
        //Save the Employee object
        session.save(employee1);
        session.save(employee2);     
        //Commit the changes
        session.getTransaction().commit();
        //Close the session
        session.close();
    }
}
  • Create the Configuration object and read the configuration file using the configure() method.
Configuration configuration = new Configuration().configure("hibernate.cfg.xml");
  • Get the SessionFactory object through the buildSessionFactory() method of the configuration object.
SessionFactory sessionFactory = configuration.buildSessionFactory(serviceRegistry);
  • openSession() method opens up the new session and begin a new transaction
Session session = sessionFactory.openSession();
session.beginTransaction();
  • Create two Employee objects and set values to its properties
Employee employee1 = new Employee();
employee1.setEmpName("Employee 1");        
Employee employee2 = new Employee();
employee2.setEmpName("Employee 2");
  • Create two Department objects and set value to it properties
 Department department1 = new Department();
 department1 .setDepName("Mechanical Department");
 Department department2 = new Department();
 department2 .setDepName("Electrical Department");
  • Create a Set and add the two department objects into it. Finally, add the Set into department property of Employee
Set s = new HashSet();
s.add(department1);
s.add(department2);
employee1.setDepartment(s);
employee2.setDepartment(s);
  • save() method of the session object will persist the employee object into the database. Since we have used cascade as all it inturn saves the department.
session.save(employee1);
session.save(employee2);
  • Finally get the transaction and commit the changes and close the session.
session.getTransaction().commit();
session.close();

Console:

INFO: HHH000261: Table found: DEPARTMENT
Nov 23, 2016 4:23:22 PM org.hibernate.tool.hbm2ddl.TableMetadata <init>
INFO: HHH000037: Columns: [dep_name, dep_id]
Nov 23, 2016 4:23:22 PM org.hibernate.tool.hbm2ddl.TableMetadata <init>
INFO: HHH000108: Foreign keys: []
Nov 23, 2016 4:23:22 PM org.hibernate.tool.hbm2ddl.TableMetadata <init>
INFO: HHH000126: Indexes: [sys_c0014545]
Nov 23, 2016 4:23:25 PM org.hibernate.tool.hbm2ddl.TableMetadata <init>
INFO: HHH000261: Table found: EMPLOYEE
Nov 23, 2016 4:23:25 PM org.hibernate.tool.hbm2ddl.TableMetadata <init>
INFO: HHH000037: Columns: [emp_name, emp_id]
Nov 23, 2016 4:23:25 PM org.hibernate.tool.hbm2ddl.TableMetadata <init>
INFO: HHH000108: Foreign keys: []
Nov 23, 2016 4:23:25 PM org.hibernate.tool.hbm2ddl.TableMetadata <init>
INFO: HHH000126: Indexes: [sys_c0014543]
Nov 23, 2016 4:23:28 PM org.hibernate.tool.hbm2ddl.TableMetadata <init>
INFO: HHH000261: Table found: EMPLOYEE_DEPARTMENT
Nov 23, 2016 4:23:28 PM org.hibernate.tool.hbm2ddl.TableMetadata <init>
INFO: HHH000037: Columns: [dep_id, emp_id]
Nov 23, 2016 4:23:28 PM org.hibernate.tool.hbm2ddl.TableMetadata <init>
INFO: HHH000108: Foreign keys: [fk_dep_id, fk_emp_id]
Nov 23, 2016 4:23:28 PM org.hibernate.tool.hbm2ddl.TableMetadata <init>
INFO: HHH000126: Indexes: [sys_c0014548]
Nov 23, 2016 4:23:28 PM org.hibernate.tool.hbm2ddl.SchemaUpdate execute
INFO: HHH000232: Schema update complete
Hibernate: select hibernate_sequence.nextval from dual
Hibernate: select hibernate_sequence.nextval from dual
Hibernate: select hibernate_sequence.nextval from dual
Hibernate: select hibernate_sequence.nextval from dual
Hibernate: insert into EMPLOYEE (EMP_NAME, EMP_ID) values (?, ?)
Hibernate: insert into DEPARTMENT (DEP_NAME, DEP_ID) values (?, ?)
Hibernate: insert into DEPARTMENT (DEP_NAME, DEP_ID) values (?, ?)
Hibernate: insert into EMPLOYEE (EMP_NAME, EMP_ID) values (?, ?)
Hibernate: insert into EMPLOYEE_DEPARTMENT (EMP_ID, DEP_ID) values (?, ?)
Hibernate: insert into EMPLOYEE_DEPARTMENT (EMP_ID, DEP_ID) values (?, ?)
Hibernate: insert into EMPLOYEE_DEPARTMENT (EMP_ID, DEP_ID) values (?, ?)
Hibernate: insert into EMPLOYEE_DEPARTMENT (EMP_ID, DEP_ID) values (?, ?)

Retrieving Employee and Department

package com.javainterviewpoint;

import java.util.List;
import java.util.Set;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;

public class RetriveData
{
    public static void main(String args[])
    {
        //Reading the hibernate configuration file
        Configuration configuration = new Configuration().configure("hibernate.cfg.xml");
        StandardServiceRegistryBuilder regBuilber = new StandardServiceRegistryBuilder();
        regBuilber.applySettings(configuration.getProperties());
        ServiceRegistry serviceRegistry = regBuilber.build();
        
        //Create SessionFacctory
        SessionFactory sessionFactory = configuration.buildSessionFactory(serviceRegistry);
        
        //Create Session from SessionFactory
        Session session = sessionFactory.openSession();
        
        // Retrieving Employee and Department
        System.out.println("*** Retrieving Department through Employee *** ");
        List empList = session.createQuery("from Employee").list();
        for(Employee employee : empList)
        {
            System.out.println("** Employee Details **");
            System.out.println("Employee Id   : "+ employee.getEmpId());
            System.out.println("Employee Name : "+  employee.getEmpName());
            
            System.out.println("** Department Details **");
            Set deparmentSet = employee.getDepartment();
            for(Department department : deparmentSet)
            {
                System.out.println("Department Id   : "+department.getDepId());
                System.out.println("Department Name : "+department.getDepName());
                System.out.println("");
            }
        }
        
        System.out.println("*** Retrieving Employee through Department *** ");
        List depList = session.createQuery("from Department").list();
        for(Department department : depList)
        {
            System.out.println("** Department Details **");
            System.out.println("Department Id   : "+ department.getDepId());
            System.out.println("Department Name : "+  department.getDepName());
            
            System.out.println("** Employee Details **");
            Set employeeSet = department.getEmployee();
            for(Employee employee : employeeSet)
            {
                System.out.println("Employee Id   : "+ employee.getEmpId());
                System.out.println("Employee Name : "+  employee.getEmpName());
                System.out.println("");
            }
        }
        //Close the session
        session.close();
    }
}

Output:

The above code shows that we can retrieve the Departments through Employee and vice-versa.

*** Retrieving Department through Employee *** 
Hibernate: select employee0_.EMP_ID as EMP_ID1_1_, employee0_.EMP_NAME as EMP_NAME2_1_ from EMPLOYEE employee0_
** Employee Details **
Employee Id   : 164
Employee Name : Employee 1
** Department Details **
Hibernate: select department0_.EMP_ID as EMP_ID1_1_0_, department0_.DEP_ID as DEP_ID2_2_0_, department1_.DEP_ID as DEP_ID1_0_1_, department1_.DEP_NAME as DEP_NAME2_0_1_ from EMPLOYEE_DEPARTMENT department0_ inner join DEPARTMENT department1_ on department0_.DEP_ID=department1_.DEP_ID where department0_.EMP_ID=?
Department Id   : 166
Department Name : Electrical Department

Department Id   : 165
Department Name : Mechanical Department

** Employee Details **
Employee Id   : 167
Employee Name : Employee 2
** Department Details **
Hibernate: select department0_.EMP_ID as EMP_ID1_1_0_, department0_.DEP_ID as DEP_ID2_2_0_, department1_.DEP_ID as DEP_ID1_0_1_, department1_.DEP_NAME as DEP_NAME2_0_1_ from EMPLOYEE_DEPARTMENT department0_ inner join DEPARTMENT department1_ on department0_.DEP_ID=department1_.DEP_ID where department0_.EMP_ID=?
Department Id   : 166
Department Name : Electrical Department

Department Id   : 165
Department Name : Mechanical Department

*** Retrieving Employee through Department *** 
Hibernate: select department0_.DEP_ID as DEP_ID1_0_, department0_.DEP_NAME as DEP_NAME2_0_ from DEPARTMENT department0_
** Department Details **
Department Id   : 165
Department Name : Mechanical Department
** Employee Details **
Hibernate: select employee0_.DEP_ID as DEP_ID2_0_0_, employee0_.EMP_ID as EMP_ID1_2_0_, employee1_.EMP_ID as EMP_ID1_1_1_, employee1_.EMP_NAME as EMP_NAME2_1_1_ from EMPLOYEE_DEPARTMENT employee0_ inner join EMPLOYEE employee1_ on employee0_.EMP_ID=employee1_.EMP_ID where employee0_.DEP_ID=?
Employee Id   : 164
Employee Name : Employee 1

Employee Id   : 167
Employee Name : Employee 2

** Department Details **
Department Id   : 166
Department Name : Electrical Department
** Employee Details **
Hibernate: select employee0_.DEP_ID as DEP_ID2_0_0_, employee0_.EMP_ID as EMP_ID1_2_0_, employee1_.EMP_ID as EMP_ID1_1_1_, employee1_.EMP_NAME as EMP_NAME2_1_1_ from EMPLOYEE_DEPARTMENT employee0_ inner join EMPLOYEE employee1_ on employee0_.EMP_ID=employee1_.EMP_ID where employee0_.DEP_ID=?
Employee Id   : 164
Employee Name : Employee 1

Employee Id   : 167
Employee Name : Employee 2

Leave a Reply

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