Many To Many XML Mapping in Hibernate
- 22nd Feb 2017
- 0
- 8339
- how many to many works in hibernate many to many in hibernate many to many relation in hibernate Many to many relation with XML in hibernate many to many relation xml mapping in hibernate many to many xml mapping Many to many XML mapping example in Hibernate Why we need temporary table in Many to many relation
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
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>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>
<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
- 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;
- }
- }
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
- 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;
- }
- }
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
- <?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>
<?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
- <?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>
<?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
- <?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>
<?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
- 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 9
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 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;
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.