Hibernate

Many to many relationship in hibernate

Published on

1. Introduction

A many-to-many mapping represents a relationship between two entities, where each entity can be associated with multiple instances of the other entity. In a many-to-many relationship between two tables, there will be an intermediate table (common table or join table) that stores the relationship between the two entities.

Hibernate create a junction table (intermediary table) while establishing many-to-many relationship between two entities & this junction table store the relationship between two entities. You can create a one-to-many mapping in Hibernate using the @ManyToMany annotation.

Download Source Code Here ⬇️

2: Example: Lets take two entity class i.e Employee & Project. Here one employee can work on many projects & one project assigned to many employee

As we can see Employee1 & Employee2 one has assigend for 5 projects & every projects has assinged to bote. it shows the many-to-many relationship.

Lets write code for this.

Create a Maven Project as below groupId is com.hiber.manytomany & artifactId is ManyToMany

Create two entity class Emp.java & Project.java for many-to-many mapping.

Create a database in mysql( I am using mysql here) by the name of manytomanydb

Create a main class called MappingDemo.java

pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <groupId>com.hiber.manytomany</groupId>
  <artifactId>ManyToMany</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <packaging>jar</packaging>

  <name>ManyToMany</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.6.6.Final</version>
		</dependency>

		<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
			<version>5.1.30</version>
		</dependency>

	</dependencies>
</project>

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>
		<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
		<property name="connection.url">jdbc:mysql://localhost:3306/manytomanydb</property>
		<property name="connection.username">root</property>
		<property name="connection.password">root</property>
		<property name = "dialect">org.hibernate.dialect.MySQL5Dialect</property>
		<property name="hbm2ddl.auto">create</property>
		<property name="show_sql">true</property>
		<mapping class="com.hiber.manytomany.Project"/>
		<mapping class="com.hiber.manytomany.Emp"/>

		
	</session-factory>
</hibernate-configuration>

Emp.java

package com.hiber.manytomany;

import java.util.List;

import javax.persistence.*;

@Entity
public class Emp {

	@Id
	private int eid;
	private String name;
	@ManyToMany
	@JoinTable(
			name="emp_project",joinColumns = {@JoinColumn(name="eid")},
			inverseJoinColumns = {@JoinColumn(name="pid")}
			)
	private List<Project> projects;
	public int getEid() {
		return eid;
	}
	public void setEid(int eid) {
		this.eid = eid;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public List<Project> getProjects() {
		return projects;
	}
	public void setProjects(List<Project> projects) {
		this.projects = projects;
	}
	public Emp() {
		super();
		// TODO Auto-generated constructor stub
	}
	public Emp(int eid, String name, List<Project> projects) {
		super();
		this.eid = eid;
		this.name = name;
		this.projects = projects;
	}
	
	

}

Project.java

package com.hiber.manytomany;

import java.util.List;

import javax.persistence.Column;
import javax.persistence.*;
import javax.persistence.ManyToMany;

@Entity
public class Project {

	@Id
	private int pid;
	@Column(name="project_name")
	private String projectName;
	
	@ManyToMany(mappedBy = "projects")
	private List<Emp> emps;

	public Project() {
		super();
		// TODO Auto-generated constructor stub
	}

	public Project(int pid, String projectName, List<Emp> emps) {
		super();
		this.pid = pid;
		this.projectName = projectName;
		this.emps = emps;
	}

	public int getPid() {
		return pid;
	}

	public void setPid(int pid) {
		this.pid = pid;
	}

	public String getProjectName() {
		return projectName;
	}

	public void setProjectName(String projectName) {
		this.projectName = projectName;
	}

	public List<Emp> getEmps() {
		return emps;
	}

	public void setEmps(List<Emp> emps) {
		this.emps = emps;
	}
	
	
	
}

Output

Database Tables

mysql> use manytomanydb;
Database changed
mysql> show tables;
+------------------------+
| Tables_in_manytomanydb |
+------------------------+
| emp                    |
| emp_learn              |
| emp_project            |
| project                |
+------------------------+
4 rows in set (0.00 sec)

mysql> select * from emp;
+-----+-------+
| eid | name  |
+-----+-------+
|  34 | Ram   |
|  35 | Shyam |
+-----+-------+
2 rows in set (0.02 sec)

mysql> select * from project;
+-------+--------------------------+
| pid   | project_name             |
+-------+--------------------------+
| 12121 | Library Managment System |
| 14214 | Chatbot                  |
+-------+--------------------------+
2 rows in set (0.01 sec)

mysql> select * from emp_project;
+-----+-------+
| eid | pid   |
+-----+-------+
|  34 | 12121 |
|  34 | 14214 |
+-----+-------+
2 rows in set (0.01 sec)

jointable

@JoinTable(
	name="emp_project",joinColumns = {@JoinColumn(name="eid")},
	inverseJoinColumns = {@JoinColumn(name="pid")}
	)
	
Here intermediate table is emp_project having one primary key (eid) 
& foreign key(pid) as shown in the above code. we can change 
both coumn name using annotation.
1:To change the Emp table primary key use  @JoinColumn(name="eid")
2:To change the Project table primary key ( here this is foreign key
in emp_project table)use inverseJoinColumns = {@JoinColumn(name="pid")

Download Source Code Here ⬇️

Click to comment

Popular Posts

Copyright © 2024 javadsa.com