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
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
Step 2
Update pom.xml with Hibernate and Mysql dependencies
- <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>
<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
- 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;
- }
- }
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
- 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;
- }
- }
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
- <?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>
<?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
- 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();
- }
- }
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
- 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");
- }
- }
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;
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.