Many To Many Annotation mapping in Hibernate

Let us understand Bidirectional Many to Many Annotation 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 temporary 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

ManyToManyAnnotationProjStructure

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>ManyToManyAnnotation</groupId>
  6.   <artifactId>ManyToManyAnnotation</artifactId>
  7.   <version>0.0.1-SNAPSHOT</version>
  8.   <packaging>jar</packaging>
  9.  
  10.   <name>ManyToManyAnnotation</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.      <!-- https://mvnrepository.com/artifact/org.hibernate/hibernate-core -->
  25.         <dependency>
  26.             <groupId>org.hibernate</groupId>
  27.             <artifactId>hibernate-core</artifactId>
  28.             <version>5.2.6.Final</version>
  29.         </dependency>
  30.         <!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
  31.         <dependency>
  32.             <groupId>mysql</groupId>
  33.             <artifactId>mysql-connector-java</artifactId>
  34.             <version>6.0.5</version>
  35.         </dependency>
  36.   </dependencies>
  37. </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>ManyToManyAnnotation</groupId>
  <artifactId>ManyToManyAnnotation</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <packaging>jar</packaging>

  <name>ManyToManyAnnotation</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. import javax.persistence.CascadeType;
  6. import javax.persistence.Column;
  7. import javax.persistence.Entity;
  8. import javax.persistence.FetchType;
  9. import javax.persistence.GeneratedValue;
  10. import javax.persistence.GenerationType;
  11. import javax.persistence.Id;
  12. import javax.persistence.JoinColumn;
  13. import javax.persistence.JoinTable;
  14. import javax.persistence.ManyToMany;
  15. import javax.persistence.Table;
  16.  
  17. @Entity
  18. @Table(name="Bank")
  19. public class Bank {
  20.    
  21.     @Id
  22.     @GeneratedValue(strategy = GenerationType.SEQUENCE)
  23.     @Column(name="Bank_Id")
  24.     private int bankId;
  25.    
  26.     @Column(name="Name")
  27.     private String name;
  28.    
  29.     @Column(name="Branch_Name")
  30.     private String branchName;
  31.    
  32.     @Column(name="Swift_Code")
  33.     private String swiftCode;
  34.    
  35.     @ManyToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL)
  36.     @JoinTable(name = "Bank_Customer",
  37.                            joinColumns = { @JoinColumn(name = "Bank_Id", nullable = false) },
  38.                inverseJoinColumns = { @JoinColumn(name = "Customer_Id",nullable = false) } )
  39.     private Set<Customer> customers;
  40.    
  41.     public int getBankId() {
  42.         return bankId;
  43.     }
  44.     public void setBankId(int bankId) {
  45.         this.bankId = bankId;
  46.     }
  47.     public String getName() {
  48.         return name;
  49.     }
  50.     public void setName(String name) {
  51.         this.name = name;
  52.     }
  53.     public String getBranchName() {
  54.         return branchName;
  55.     }
  56.     public void setBranchName(String branchName) {
  57.         this.branchName = branchName;
  58.     }
  59.     public String getSwiftCode() {
  60.         return swiftCode;
  61.     }
  62.     public void setSwiftCode(String swiftCode) {
  63.         this.swiftCode = swiftCode;
  64.     }
  65.     public Set<Customer> getCustomers() {
  66.         return customers;
  67.     }
  68.     public void setCustomers(Set<Customer> customers) {
  69.         this.customers = customers;
  70.     }
  71.  
  72. }
package com.kb.model;

import java.util.Set;

import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
import javax.persistence.Table;

@Entity
@Table(name="Bank")
public class Bank {
	
	@Id
	@GeneratedValue(strategy = GenerationType.SEQUENCE)
	@Column(name="Bank_Id")
	private int bankId;
	
	@Column(name="Name")
	private String name;
	
	@Column(name="Branch_Name")
	private String branchName;
	
	@Column(name="Swift_Code")
	private String swiftCode;
	
	@ManyToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL)
	@JoinTable(name = "Bank_Customer", 
                           joinColumns = { @JoinColumn(name = "Bank_Id", nullable = false) },
			   inverseJoinColumns = { @JoinColumn(name = "Customer_Id",nullable = false) } )
	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;
	}

}


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

We have defined Many to Many mapping with Customer entity using @ManyToMany annotation

fetch = FetchType.LAZY : Indicates we are preferring lazy loading.

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.

@JoinTable – Is used to define the join table (link table) for many-to-many relationship.

It is specified on the owner side of a many-to-many relationship

In our case the join table is Bank_Customer

If we don’t specify @JoinTable annotation,the default values of the annotation elements apply.

The name of the join table is considered as table names of the associated primary tables concatenated together (owning side first) using an underscore.

@JoinColumn – Is used to define the join column in Link table considering the primary key of both main tables.

Step 4

Create Customer class

  1. package com.kb.model;
  2.  
  3. import java.util.Set;
  4.  
  5. import javax.persistence.Column;
  6. import javax.persistence.Entity;
  7. import javax.persistence.FetchType;
  8. import javax.persistence.GeneratedValue;
  9. import javax.persistence.GenerationType;
  10. import javax.persistence.Id;
  11. import javax.persistence.ManyToMany;
  12. import javax.persistence.Table;
  13.  
  14. @Entity
  15. @Table(name="Customer")
  16. public class Customer {
  17.    
  18.     @Id
  19.     @GeneratedValue(strategy = GenerationType.SEQUENCE)
  20.     @Column(name="Customer_Id")
  21.     private int customerId;
  22.    
  23.     @Column(name="Name")
  24.     private String name;
  25.    
  26.     @Column(name="Email")
  27.     private String email;
  28.    
  29.     @Column(name="Mobile_No")
  30.     private long mobileNo;
  31.    
  32.     @ManyToMany(fetch = FetchType.LAZY, mappedBy = "customers")
  33.     private Set<Bank> banks;
  34.    
  35.     public int getCustomerId() {
  36.         return customerId;
  37.     }
  38.     public void setCustomerId(int customerId) {
  39.         this.customerId = customerId;
  40.     }
  41.     public String getName() {
  42.         return name;
  43.     }
  44.     public void setName(String name) {
  45.         this.name = name;
  46.     }
  47.     public String getEmail() {
  48.         return email;
  49.     }
  50.     public void setEmail(String email) {
  51.         this.email = email;
  52.     }
  53.     public long getMobileNo() {
  54.         return mobileNo;
  55.     }
  56.     public void setMobileNo(long mobileNo) {
  57.         this.mobileNo = mobileNo;
  58.     }
  59.     public Set<Bank> getBanks() {
  60.         return banks;
  61.     }
  62.     public void setBanks(Set<Bank> banks) {
  63.         this.banks = banks;
  64.     }
  65. }
package com.kb.model;

import java.util.Set;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.ManyToMany;
import javax.persistence.Table;

@Entity
@Table(name="Customer")
public class Customer {
	
	@Id
	@GeneratedValue(strategy = GenerationType.SEQUENCE)
	@Column(name="Customer_Id")
	private int customerId;
	
	@Column(name="Name")
	private String name;
	
	@Column(name="Email")
	private String email;
	
	@Column(name="Mobile_No")
	private long mobileNo;
	
	@ManyToMany(fetch = FetchType.LAZY, mappedBy = "customers")
	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;
	}
}


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

We have defined Many to Many mapping with Bank entity using @ManyToMany annotation

fetch = FetchType.LAZY : Indicates we are preferring lazy loading

mappedBy” instructs to hibernate that mapping is already done in another class(owner side of a relation).

If we don’t do use “mappedBy” Hibernate will map these two relations separately assuming it’s not the same relation.

so we need to tell hibernate to do the mapping on one side only and coordinate between this relation.

Step 5

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 class="com.kb.model.Bank" />
  35.     <mapping class="com.kb.model.Customer" />
  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 class="com.kb.model.Bank" />
	<mapping class="com.kb.model.Customer" />
 
   </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 class names using < mapping > tag.

Step 6

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 7

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 8

Run the above class to check the output

Hibernate: 
    
    create table Bank (

       Bank_Id integer not null,

        Branch_Name varchar(255),

        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,

        Email varchar(255),

        Mobile_No bigint,

        Name varchar(255),

        primary key (Customer_Id)
    )


Hibernate: 
    
    create table hibernate_sequence (
       next_val bigint
    )


Hibernate: 
    
    insert into hibernate_sequence values ( 1 )


Hibernate: 
    
    insert into hibernate_sequence values ( 1 )


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
        next_val as id_val 

    from
        hibernate_sequence for update
            

Hibernate: 

    update
        hibernate_sequence 

    set
        next_val= ? 

    where
        next_val=?


Hibernate: 

    select
        next_val as id_val 

    from
        hibernate_sequence for update

            
Hibernate: 

    update
        hibernate_sequence 

    set
        next_val= ? 

    where
        next_val=?


Hibernate: 

    select
        next_val as id_val 

    from
        hibernate_sequence for update

            
Hibernate: 

    update
        hibernate_sequence 

    set
        next_val= ? 

    where
        next_val=?


Hibernate: 

    select
        next_val as id_val 

    from
        hibernate_sequence for update

            
Hibernate: 

    update
        hibernate_sequence 

    set
        next_val= ? 

    where
        next_val=?


Hibernate: 

    select
        next_val as id_val 

    from
        hibernate_sequence for update

            
Hibernate: 

    update
        hibernate_sequence 

    set
        next_val= ? 

    where
        next_val=?


Hibernate: 

    select
        next_val as id_val 

    from
        hibernate_sequence for update

            
Hibernate: 

    update
        hibernate_sequence 

    set
        next_val= ? 

    where
        next_val=?


Hibernate: 

    insert 

    into
        Bank
        (Branch_Name, Name, Swift_Code, Bank_Id) 

    values
        (?, ?, ?, ?)


Hibernate: 

    insert 

    into
        Customer
        (Email, Mobile_No, Name, Customer_Id) 

    values
        (?, ?, ?, ?)


Hibernate: 

    insert 

    into
        Customer
        (Email, Mobile_No, Name, Customer_Id) 

    values
        (?, ?, ?, ?)


Hibernate: 

    insert 

    into
        Bank
        (Branch_Name, Name, Swift_Code, Bank_Id) 

    values
        (?, ?, ?, ?)


Hibernate: 

    insert 

    into
        Customer
        (Email, Mobile_No, Name, Customer_Id) 

    values
        (?, ?, ?, ?)


Hibernate: 

    insert 

    into
        Customer
        (Email, Mobile_No, Name, 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;

ManyToManyAnnotationOutput

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 ManyToManyAnnotation.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