Many To Many XML Mapping in Hibernate

Let us understand Bidirectional Many to Many XML Mapping in Hibernate

In this relation mapping, one object of a class ‘X’ is associated with multiple objects of class ‘Y’ and one object of class ‘y’ is associated with multiple objects of class ‘X’.

In other words

One record of a table ‘A’ is associated with multiple records of table ‘B’ and One record of a table ‘B’ is associated with multiple records of table ‘A’.

In this mapping, an additional table called “Join table” is required to store the primary keys of both the tables as a foreign keys.

We need to instruct Hibernate how the Join table has to be constructed.

Example:

Consider Bank and Customer

One Bank can have multiple customers and One customer can have multiple bank accounts.

Relation looks as below

ManyToMany_ERD

As shown in the above ER diagram,Relation between Bank and Customer is Many To Many.

Customer_Id is the primary key for Customer table

Bank_Id is the primary key for Bank table

We can see that both Customer_Id and Bank_Id are stored in a Join table called “Bank_Customer

Let’s implement this project step by step

Step 1

Create hibernate project

Please refer Hibernate setup in eclipse article on how to do it.

Project structure

ManyToManyXMLProjStructure

Step 2

Update pom.xml with Hibernate and Mysql dependencies

  1. <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  2.   xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  3.   <modelVersion>4.0.0</modelVersion>
  4.  
  5.   <groupId>ManyToManyXML</groupId>
  6.   <artifactId>ManyToManyXML</artifactId>
  7.   <version>0.0.1-SNAPSHOT</version>
  8.   <packaging>jar</packaging>
  9.  
  10.   <name>ManyToManyXML</name>
  11.   <url>http://maven.apache.org</url>
  12.  
  13.   <properties>
  14.     <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  15.   </properties>
  16.  
  17.   <dependencies>
  18.     <dependency>
  19.       <groupId>junit</groupId>
  20.       <artifactId>junit</artifactId>
  21.       <version>3.8.1</version>
  22.       <scope>test</scope>
  23.     </dependency>
  24.  
  25.      <!-- https://mvnrepository.com/artifact/org.hibernate/hibernate-core -->
  26.         <dependency>
  27.             <groupId>org.hibernate</groupId>
  28.             <artifactId>hibernate-core</artifactId>
  29.             <version>5.2.6.Final</version>
  30.         </dependency>
  31.  
  32.         <!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
  33.         <dependency>
  34.             <groupId>mysql</groupId>
  35.             <artifactId>mysql-connector-java</artifactId>
  36.             <version>6.0.5</version>
  37.         </dependency>
  38.  
  39.   </dependencies>
  40. </project>
<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>ManyToManyXML</groupId>
  <artifactId>ManyToManyXML</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <packaging>jar</packaging>

  <name>ManyToManyXML</name>
  <url>http://maven.apache.org</url>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  </properties>

  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>3.8.1</version>
      <scope>test</scope>
    </dependency>

     <!-- https://mvnrepository.com/artifact/org.hibernate/hibernate-core -->
		<dependency>
			<groupId>org.hibernate</groupId>
			<artifactId>hibernate-core</artifactId>
			<version>5.2.6.Final</version>
		</dependency>

		<!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
		<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
			<version>6.0.5</version>
		</dependency>

  </dependencies>
</project>

Step 3

Create Bank class

  1. package com.kb.model;
  2.  
  3. import java.util.Set;
  4.  
  5. public class Bank {
  6.     private int bankId;
  7.     private String name;
  8.     private String branchName;
  9.     private String swiftCode;
  10.     private Set<Customer> customers;
  11.    
  12.     public int getBankId() {
  13.         return bankId;
  14.     }
  15.     public void setBankId(int bankId) {
  16.         this.bankId = bankId;
  17.     }
  18.     public String getName() {
  19.         return name;
  20.     }
  21.     public void setName(String name) {
  22.         this.name = name;
  23.     }
  24.     public String getBranchName() {
  25.         return branchName;
  26.     }
  27.     public void setBranchName(String branchName) {
  28.         this.branchName = branchName;
  29.     }
  30.     public String getSwiftCode() {
  31.         return swiftCode;
  32.     }
  33.     public void setSwiftCode(String swiftCode) {
  34.         this.swiftCode = swiftCode;
  35.     }
  36.     public Set<Customer> getCustomers() {
  37.         return customers;
  38.     }
  39.     public void setCustomers(Set<Customer> customers) {
  40.         this.customers = customers;
  41.     }
  42.  
  43. }
package com.kb.model;

import java.util.Set;

public class Bank {
	private int bankId;
	private String name;
	private String branchName;
	private String swiftCode;
	private Set<Customer> customers;
	
	public int getBankId() {
		return bankId;
	}
	public void setBankId(int bankId) {
		this.bankId = bankId;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getBranchName() {
		return branchName;
	}
	public void setBranchName(String branchName) {
		this.branchName = branchName;
	}
	public String getSwiftCode() {
		return swiftCode;
	}
	public void setSwiftCode(String swiftCode) {
		this.swiftCode = swiftCode;
	}
	public Set<Customer> getCustomers() {
		return customers;
	}
	public void setCustomers(Set<Customer> customers) {
		this.customers = customers;
	}

}


In this class, we have added Collection of Customers to have many to many relation

Step 4

Create Customer class

  1. package com.kb.model;
  2.  
  3. import java.util.Set;
  4.  
  5. public class Customer {
  6.     private int customerId;
  7.     private String name;
  8.     private String email;
  9.     private long mobileNo;
  10.     private Set<Bank> banks;
  11.    
  12.     public int getCustomerId() {
  13.         return customerId;
  14.     }
  15.     public void setCustomerId(int customerId) {
  16.         this.customerId = customerId;
  17.     }
  18.     public String getName() {
  19.         return name;
  20.     }
  21.     public void setName(String name) {
  22.         this.name = name;
  23.     }
  24.     public String getEmail() {
  25.         return email;
  26.     }
  27.     public void setEmail(String email) {
  28.         this.email = email;
  29.     }
  30.     public long getMobileNo() {
  31.         return mobileNo;
  32.     }
  33.     public void setMobileNo(long mobileNo) {
  34.         this.mobileNo = mobileNo;
  35.     }
  36.     public Set<Bank> getBanks() {
  37.         return banks;
  38.     }
  39.     public void setBanks(Set<Bank> banks) {
  40.         this.banks = banks;
  41.     }
  42. }
package com.kb.model;

import java.util.Set;

public class Customer {
	private int customerId;
	private String name;
	private String email;
	private long mobileNo;
	private Set<Bank> banks;
	
	public int getCustomerId() {
		return customerId;
	}
	public void setCustomerId(int customerId) {
		this.customerId = customerId;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getEmail() {
		return email;
	}
	public void setEmail(String email) {
		this.email = email;
	}
	public long getMobileNo() {
		return mobileNo;
	}
	public void setMobileNo(long mobileNo) {
		this.mobileNo = mobileNo;
	}
	public Set<Bank> getBanks() {
		return banks;
	}
	public void setBanks(Set<Bank> banks) {
		this.banks = banks;
	}
}


In this class, we have added Collection of Banks to have many to many relation

Step 5

Create bank.hbm.xml

  1. <?xml version='1.0' encoding='UTF-8'?>  
  2. <!DOCTYPE hibernate-mapping PUBLIC  
  3.           "-//Hibernate/Hibernate Mapping DTD 3.0//EN"  
  4.           "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
  5.  
  6. <hibernate-mapping package="com.kb.model">
  7.     <class name="Bank" table="Bank">
  8.  
  9.         <id name="bankId" type="int">
  10.             <column name="Bank_Id" />
  11.             <generator class="increment" />
  12.         </id>
  13.  
  14.         <property name="name" column="Name" />
  15.         <property name="branchName" column="Branch_Name" />
  16.         <property name="swiftCode" column="Swift_Code" />
  17.         <set name="customers" table="Bank_Customer"
  18.             inverse="false" lazy="true" fetch="select" cascade="all">
  19.             <key column="Bank_Id" />
  20.             <many-to-many column="Customer_Id" class="Customer" />
  21.         </set>
  22.     </class>
  23. </hibernate-mapping>  
<?xml version='1.0' encoding='UTF-8'?>  
<!DOCTYPE hibernate-mapping PUBLIC  
          "-//Hibernate/Hibernate Mapping DTD 3.0//EN"  
          "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">

<hibernate-mapping package="com.kb.model">
	<class name="Bank" table="Bank">

		<id name="bankId" type="int">
			<column name="Bank_Id" />
			<generator class="increment" />
		</id>

		<property name="name" column="Name" />
		<property name="branchName" column="Branch_Name" />
		<property name="swiftCode" column="Swift_Code" />
		<set name="customers" table="Bank_Customer"
			inverse="false" lazy="true" fetch="select" cascade="all">
			<key column="Bank_Id" />
			<many-to-many column="Customer_Id" class="Customer" />
		</set>
	</class>
</hibernate-mapping>  


In this mapping file,We have defined the Table mapping for Bank class.

We have specified Primary key as bankId and generator class as “increment” for automatic primary key generation.

We have defined Many to Many mapping with Customer entity using < set > and < many-to-many > tag.

We have also provided lazy = true to achieve lazy loading

fetch = select to inform hibernate to generate separate select query while retrieving Customers

inverse = true is used to decide which side is the relationship owner to manage the relationship

inverse = false in above xml indicates that Bank is the relationship owner.

We have given cascade as ALL, after performing one operation (save, update and delete) on Bank entity, it calls those operations (save, update and delete) on Customer entity.

Step 6

Create customer.hbm.xml

  1. <?xml version='1.0' encoding='UTF-8'?>  
  2. <!DOCTYPE hibernate-mapping PUBLIC  
  3.           "-//Hibernate/Hibernate Mapping DTD 3.0//EN"  
  4.           "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
  5.  
  6. <hibernate-mapping package="com.kb.model">
  7.     <class name="Customer" table="Customer">
  8.         <id name="customerId" type="int">
  9.             <column name="Customer_Id"></column>
  10.             <generator class="increment"></generator>
  11.         </id>
  12.         <property name="name" column="Name"></property>
  13.         <property name="email" column="Email"></property>
  14.         <property name="mobileNo" type="int" column="Mobile_No"></property>
  15.  
  16.         <set name="banks" table="Bank_Customer"
  17.             inverse="true" lazy="true" fetch="select">
  18.             <key column="Customer_Id" />
  19.             <many-to-many column="Bank_Id" class="Bank" />
  20.         </set>
  21.     </class>
  22. </hibernate-mapping>  
<?xml version='1.0' encoding='UTF-8'?>  
<!DOCTYPE hibernate-mapping PUBLIC  
          "-//Hibernate/Hibernate Mapping DTD 3.0//EN"  
          "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">

<hibernate-mapping package="com.kb.model">
	<class name="Customer" table="Customer">
		<id name="customerId" type="int">
			<column name="Customer_Id"></column>
			<generator class="increment"></generator>
		</id>
		<property name="name" column="Name"></property>
		<property name="email" column="Email"></property>
		<property name="mobileNo" type="int" column="Mobile_No"></property>

		<set name="banks" table="Bank_Customer"
			inverse="true" lazy="true" fetch="select">
			<key column="Customer_Id" />
			<many-to-many column="Bank_Id" class="Bank" />
		</set>
	</class>
</hibernate-mapping>  


In this mapping file, We have defined the Table mapping for Customer class.

We have specified Primary key as customerId and generator class as “increment”.

We have defined Many to Many mapping with Bank entity using < set > and < many-to-many > tag.

We have also provided fetch = select to inform hibernate to generate separate select query while retreivng Banks(used for lazy loading)

Step 7

Create hibernate.cfg.xml

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <!DOCTYPE hibernate-configuration PUBLIC
  3.        "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
  4.        "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
  5.  
  6. <hibernate-configuration>
  7.  
  8.    <session-factory>
  9.  
  10.        <!-- Database connection properties -->
  11.        <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
  12.        <property name="connection.url">jdbc:mysql://localhost/javainsimpleway</property>
  13.        <property name="connection.username">root</property>
  14.        <property name="connection.password">root</property>
  15.  
  16.        <!-- JDBC connection pool (using the built-in) -->
  17.        <property name="connection.pool_size">100</property>
  18.  
  19.        <!-- SQL dialect -->
  20.        <property name="dialect">org.hibernate.dialect.MySQLDialect</property>
  21.  
  22.        <!-- Disable the second-level cache -->
  23.        <property name="cache.provider_class">org.hibernate.cache.internal.NoCacheProvider</property>
  24.  
  25.        <!-- Echo all executed SQL to stdout -->
  26.        <property name="show_sql">true</property>
  27.        
  28.        <!-- Format the generated Sql -->
  29.        <property name="format_sql">true</property>
  30.  
  31.        <!-- Dont Drop and re-create the database schema on startup,Just update it -->
  32.        <property name="hbm2ddl.auto">update</property>
  33.  
  34.        <mapping resource="com/kb/mapping/bank.hbm.xml"/>
  35.        <mapping resource="com/kb/mapping/customer.hbm.xml"/>
  36.  
  37.    </session-factory>
  38.  
  39. </hibernate-configuration>
<?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 properties -->
       <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
       <property name="connection.url">jdbc:mysql://localhost/javainsimpleway</property>
       <property name="connection.username">root</property>
       <property name="connection.password">root</property>
 
       <!-- JDBC connection pool (using the built-in) -->
       <property name="connection.pool_size">100</property>
 
       <!-- SQL dialect -->
       <property name="dialect">org.hibernate.dialect.MySQLDialect</property>
 
       <!-- Disable the second-level cache -->
       <property name="cache.provider_class">org.hibernate.cache.internal.NoCacheProvider</property>
 
       <!-- Echo all executed SQL to stdout -->
       <property name="show_sql">true</property>
       
       <!-- Format the generated Sql -->
       <property name="format_sql">true</property>
 
       <!-- Dont Drop and re-create the database schema on startup,Just update it -->
       <property name="hbm2ddl.auto">update</property>
 
       <mapping resource="com/kb/mapping/bank.hbm.xml"/>
       <mapping resource="com/kb/mapping/customer.hbm.xml"/>
 
   </session-factory>
 
</hibernate-configuration> 


We have defined all the database configuration in this file

hbm2ddl.auto property is defined in the config file which helps in automatic creation of tables in the database based on the mapping.

We have also provided the mapping xml file location using < mapping > tag.

Step 8

Create Hibernate util class

  1. package com.kb.util;
  2.  
  3. import org.hibernate.SessionFactory;
  4. import org.hibernate.cfg.Configuration;
  5.  
  6. public class HibernateUtil {
  7.     private static final SessionFactory sessionFactory = buildSessionFactory();
  8.  
  9.     private static SessionFactory buildSessionFactory() {
  10.         try {
  11.             // Create the SessionFactory from hibernate.cfg.xml
  12.             return new Configuration().configure().buildSessionFactory();
  13.         } catch (Throwable ex) {
  14.             // Make sure you log the exception to track it
  15.             System.err.println("SessionFactory creation failed." + ex);
  16.             throw new ExceptionInInitializerError(ex);
  17.         }
  18.     }
  19.  
  20.     public static SessionFactory getSessionFactory() {
  21.         return sessionFactory;
  22.     }
  23.    
  24.     public static void shutdown() {
  25.         // Optional but can be used to Close caches and connection pools
  26.         getSessionFactory().close();
  27.     }
  28.  
  29. }
package com.kb.util;

import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

public class HibernateUtil {
	private static final SessionFactory sessionFactory = buildSessionFactory();

    private static SessionFactory buildSessionFactory() {
        try {
            // Create the SessionFactory from hibernate.cfg.xml
            return new Configuration().configure().buildSessionFactory();
        } catch (Throwable ex) {
            // Make sure you log the exception to track it
            System.err.println("SessionFactory creation failed." + ex);
            throw new ExceptionInInitializerError(ex);
        }
    }

    public static SessionFactory getSessionFactory() {
        return sessionFactory;
    }
    
    public static void shutdown() {
    	// Optional but can be used to Close caches and connection pools
    	getSessionFactory().close();
    }

}

Step 9

Create main class to interact with DB

  1. package com.kb.db;
  2.  
  3. import java.util.HashSet;
  4. import java.util.Set;
  5.  
  6. import org.hibernate.Session;
  7. import org.hibernate.SessionFactory;
  8. import org.hibernate.Transaction;
  9.  
  10. import com.kb.model.Bank;
  11. import com.kb.model.Customer;
  12. import com.kb.util.HibernateUtil;
  13.  
  14. public class Main {
  15.     public static void main(String[] args) {
  16.         // Get session factory using Hibernate Util class
  17.         SessionFactory sf = HibernateUtil.getSessionFactory();
  18.         // Get session from Sesson factory
  19.         Session session = sf.openSession();
  20.  
  21.         // Begin transaction
  22.         Transaction t = session.beginTransaction();
  23.        
  24.         //Create Applicant Model data
  25.         Bank bank1 = new Bank();
  26.         bank1.setName("HDFC");
  27.         bank1.setBranchName("Bangalore");
  28.         bank1.setSwiftCode("HDFCINBBCOC");
  29.        
  30.         Bank bank2 = new Bank();
  31.         bank2.setName("Bank Of America");
  32.         bank2.setBranchName("California");
  33.         bank2.setSwiftCode("BOFAUS3N");
  34.        
  35.         Set<Bank> banks = new HashSet<>();
  36.         banks.add(bank1);
  37.         banks.add(bank2);
  38.  
  39.         Customer customer1 = new Customer();
  40.         customer1.setEmail("john@gmail.com");
  41.         customer1.setName("John");
  42.         customer1.setMobileNo(9999999999l);
  43.        
  44.         Customer customer2 = new Customer();
  45.         customer2.setEmail("Peter@gmail.com");
  46.         customer2.setName("Peter");
  47.         customer2.setMobileNo(8888888888l);
  48.        
  49.         Customer customer3 = new Customer();
  50.         customer3.setEmail("James@gmail.com");
  51.         customer3.setName("James");
  52.         customer3.setMobileNo(7777777777l);
  53.        
  54.         Customer customer4 = new Customer();
  55.         customer4.setEmail("Raj@gmail.com");
  56.         customer4.setName("Raj");
  57.         customer4.setMobileNo(6666666666l);
  58.        
  59.        
  60.         Set<Customer> customersList1 = new HashSet<>();
  61.         customersList1.add(customer1);
  62.         customersList1.add(customer2);
  63.         bank1.setCustomers(customersList1);
  64.        
  65.         Set<Customer> customersList2 = new HashSet<>();
  66.         customersList2.add(customer2);
  67.         customersList2.add(customer3);
  68.         customersList2.add(customer4);
  69.         bank2.setCustomers(customersList2);
  70.        
  71.         session.save(bank1);
  72.         session.save(bank2);
  73.  
  74.         // Commit the transaction and close the session
  75.         t.commit();
  76.         session.close();
  77.         System.out.println("successfully persisted Bank and Customer details");
  78.     }
  79.  
  80. }
package com.kb.db;

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

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;

import com.kb.model.Bank;
import com.kb.model.Customer;
import com.kb.util.HibernateUtil;

public class Main {
	public static void main(String[] args) {
		// Get session factory using Hibernate Util class
		SessionFactory sf = HibernateUtil.getSessionFactory();
		// Get session from Sesson factory
		Session session = sf.openSession();

		// Begin transaction
		Transaction t = session.beginTransaction();
		
		//Create Applicant Model data
		Bank bank1 = new Bank();
		bank1.setName("HDFC");
		bank1.setBranchName("Bangalore");
		bank1.setSwiftCode("HDFCINBBCOC");
		
		Bank bank2 = new Bank();
		bank2.setName("Bank Of America");
		bank2.setBranchName("California");
		bank2.setSwiftCode("BOFAUS3N");
		
		Set<Bank> banks = new HashSet<>();
		banks.add(bank1);
		banks.add(bank2);

		Customer customer1 = new Customer();
		customer1.setEmail("john@gmail.com");
		customer1.setName("John");
		customer1.setMobileNo(9999999999l);
		
		Customer customer2 = new Customer();
		customer2.setEmail("Peter@gmail.com");
		customer2.setName("Peter");
		customer2.setMobileNo(8888888888l);
		
		Customer customer3 = new Customer();
		customer3.setEmail("James@gmail.com");
		customer3.setName("James");
		customer3.setMobileNo(7777777777l);
		
		Customer customer4 = new Customer();
		customer4.setEmail("Raj@gmail.com");
		customer4.setName("Raj");
		customer4.setMobileNo(6666666666l);
		
		
		Set<Customer> customersList1 = new HashSet<>();
		customersList1.add(customer1);
		customersList1.add(customer2);
		bank1.setCustomers(customersList1);
		
		Set<Customer> customersList2 = new HashSet<>();
		customersList2.add(customer2);
		customersList2.add(customer3);
		customersList2.add(customer4);
		bank2.setCustomers(customersList2);
		
		session.save(bank1);
		session.save(bank2);

		// Commit the transaction and close the session
		t.commit();
		session.close();
		System.out.println("successfully persisted Bank and Customer details");
	}

}


We have created 2 Banks and associated multiple customers to each bank.

Bank 1 “HDFC” is associated with 2 customers Peter and John.

Bank 2 “Bank Of America” is associated with 3 customers Peter,James and Raj.

Customer “Peter” is associated to both the Banks.

Step 10

Run the above class to check the output

Hibernate:

create table Bank (

       Bank_Id integer not null,

        Name varchar(255),

        Branch_Name varchar(255),

        Swift_Code varchar(255),

        primary key (Bank_Id)
    )


Hibernate: 
    
    create table Bank_Customer (

       Bank_Id integer not null,

        Customer_Id integer not null,

        primary key (Bank_Id, Customer_Id)
    )


Hibernate: 
    
    create table Customer (

       Customer_Id integer not null,

        Name varchar(255),

        Email varchar(255),

        Mobile_No bigint,

        primary key (Customer_Id)
    )


Hibernate: 
    
    alter table Bank_Customer 

       add constraint FK526d24oq9iv9ybrokcy31m0pk 

       foreign key (Customer_Id) 
       references Customer (Customer_Id)


Hibernate: 
    
    alter table Bank_Customer 

       add constraint FKbfr3fid9w018yss48c83tlfdg 

       foreign key (Bank_Id) 
       references Bank (Bank_Id)


Hibernate: 

    select
        max(Bank_Id) 

    from
        Bank


Hibernate: 

    select
        max(Customer_Id) 

    from
        Customer


Hibernate: 

    insert 

    into
        Bank
        (Name, Branch_Name, Swift_Code, Bank_Id) 

    values
        (?, ?, ?, ?)


Hibernate: 

    insert 

    into
        Customer
        (Name, Email, Mobile_No, Customer_Id) 

    values
        (?, ?, ?, ?)


Hibernate: 

    insert 

    into
        Customer
        (Name, Email, Mobile_No, Customer_Id) 

    values
        (?, ?, ?, ?)


Hibernate: 

    insert 

    into
        Bank
        (Name, Branch_Name, Swift_Code, Bank_Id) 

    values
        (?, ?, ?, ?)


Hibernate: 

    insert 

    into
        Customer
        (Name, Email, Mobile_No, Customer_Id) 

    values
        (?, ?, ?, ?)


Hibernate: 

    insert 

    into
        Customer
        (Name, Email, Mobile_No, Customer_Id) 

    values
        (?, ?, ?, ?)


Hibernate: 

    insert 

    into
        Bank_Customer
        (Bank_Id, Customer_Id) 

    values
        (?, ?)


Hibernate: 

    insert 

    into
        Bank_Customer
        (Bank_Id, Customer_Id) 

    values
        (?, ?)


Hibernate: 

    insert 

    into
        Bank_Customer
        (Bank_Id, Customer_Id) 

    values
        (?, ?)


Hibernate: 

    insert 

    into
        Bank_Customer
        (Bank_Id, Customer_Id) 

    values
        (?, ?)


Hibernate: 

    insert 

    into
        Bank_Customer
        (Bank_Id, Customer_Id) 

    values
        (?, ?)

successfully persisted Bank and Customer details 


We can see that Create statement is executed for creating both Bank and Customer tables.

We can see that Foreign key constraint is created on third table referencing the primary key of both the tables.

Check Table in MYSQL console

E:\MySql_Install\bin
Mysql –u root –p
Enter password

Use javainsimpleway;

Select * from bank;

Select * from customer;

Select * from bank_customer;

ManyToManyXMLOutput

We can see that primary key of Bank table and Customer table are stored in Bank_Customer table.

Bank 1 “HDFC” is associated with 2 customers Peter and John.

Bank 2 “Bank Of America” is associated with 3 customers Peter,James and Raj.

Customer “Peter” is associated to both the Banks.

Note: In Many To Many relation,Third table will be created to hold the primary keys of both the tables.


Download this project ManyToManyXML.zip

About the Author

Founder of javainsimpleway.com
I love Java and open source technologies and very much passionate about software development.
I like to share my knowledge with others especially on technology 🙂
I have given all the examples as simple as possible to understand for the beginners.
All the code posted on my blog is developed,compiled and tested in my development environment.
If you find any mistakes or bugs, Please drop an email to kb.knowledge.sharing@gmail.com

Connect with me on Facebook for more updates

Share this article on