Master java skills

Hiberate Many-to-Many Mapping

Let’s understand many-to-many relationship as following:

One doctor can have many clinic addresses. Similarly, one clinic address can have many doctors (like in hospitals, many doctors work). Such relationship is called as many-to-many.

Please note that in this scenario, 3 tables would be created. One table will have relationship between doc_id and address_id. Let’s have a look at the tables

Doctor table

Address table

Third table Doctor_clinic_address. This table contains relationship between Doctor and Address table using their primary keys.

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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>com.sks</groupId>
	<artifactId>HibernateExample</artifactId>
	<version>0.0.1-SNAPSHOT</version>

<dependencies>
    <dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate-core</artifactId>
        <version>6.0.0.Alpha5</version>
    </dependency>
    <dependency>
        <groupId>com.oracle</groupId>
        <artifactId>ojdbc8</artifactId>
        <version>19.3</version>
    </dependency>
</dependencies>

</project>

Create Doctor class

package com.javatrainingschool;

import java.util.List;

import javax.persistence.CascadeType;
import javax.persistence.Entity;
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 = "doctor_3")
public class Doctor {

	@Id
	@GeneratedValue(strategy = GenerationType.AUTO)
	private int id;
	private String name;

	@ManyToMany(targetEntity=Address.class,cascade={CascadeType.ALL})
	@JoinTable(name = "doctor_clinic_address_3", joinColumns = {@JoinColumn(name = "doc_id")},
	inverseJoinColumns = {@JoinColumn(name = "add_id")})
	private List<Address> clinicAddresses;

	//getter and setter methods
	//constructors

}

Address class

package com.javatrainingschool;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name = "address_3")
public class Address {

	@Id
	@GeneratedValue(strategy = GenerationType.AUTO)
	private int addId;
	private String addLine;
	private String city;
	private String country;

	//getter and setter methods
	//constructors

}

Hibernate mapping file

<?xml version='1.0' encoding='UTF-8'?>  
<!DOCTYPE hibernate-configuration PUBLIC  
          "-//Hibernate/Hibernate Configuration DTD 3.0//EN"  
          "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">

<hibernate-configuration>

	<session-factory>

		<property name="hbm2ddl.auto">update</property>
		<property name="dialect">org.hibernate.dialect.Oracle9iDialect</property>
		<property name="connection.url">jdbc:oracle:thin:@localhost:1521/xepdb1</property>
		<property name="connection.username">singh</property>
		<property name="connection.password">azad</property>
		<property name="connection.driver_class">oracle.jdbc.driver.OracleDriver</property>
		<mapping class="com.javatrainingschool.Doctor" />
		<mapping class="com.javatrainingschool.Address" />
	</session-factory>

</hibernate-configuration>

Main testing class – DoctorMainTesting

package com.javatrainingschool;

import java.util.ArrayList;
import java.util.List;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.boot.Metadata;
import org.hibernate.boot.MetadataSources;
import org.hibernate.boot.registry.StandardServiceRegistry;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;

public class DoctorMainTesting {
	
	
	public static void main(String[] args) {
		
		
		StandardServiceRegistry ssr = new StandardServiceRegistryBuilder().configure("hibernate.cfg.xml").build();  
	    Metadata meta = new MetadataSources(ssr).getMetadataBuilder().build();  
	      
	    SessionFactory factory = meta.getSessionFactoryBuilder().build();  
	    Session session = factory.openSession();  
	      
	    Transaction t = session.beginTransaction();    
	        
	    Address add1 = new Address();
	    add1.setAddLine("Clinic Add 1");
	    add1.setCity("Kanpur");
	    add1.setCountry("India");
	    
	    Address add2 = new Address();
	    add2.setAddLine("Clinic Add 2");
	    add2.setCity("Kanpur");
	    add2.setCountry("India");
	    
	    List<Address> addresses = new ArrayList<>();
	    
	    addresses.add(add1);
	    addresses.add(add2);
	    
	    Doctor d1 = new Doctor();
	    d1.setName("Dr Bean");
	    d1.setClinicAddresses(addresses);
	    
	    session.persist(d1);
	    
	    System.out.println("Data saved successfully.");
	    
	    t.commit();
	    session.close();
	    factory.close();
	}
	
}

Many to many example 2

This example is done using MySql as database.

In this example, there is many-to-many relationship in Freelancer and Company class objects.

One freelancer can work in many companies. And one company can employ many freelancers.

FreeLancerEmployee class

package com.javatrainingschool;

import java.util.List;
import javax.persistence.CascadeType;
import javax.persistence.Entity;
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 = "free_l_employee")
public class FreeLancerEmployee {
	
	@Id
	@GeneratedValue(strategy = GenerationType.AUTO)
	private int id;
	private String name;
	private int age;
	
	@ManyToMany(targetEntity = Company.class, cascade = CascadeType.ALL)
	@JoinTable(name = "free_lancer_company", joinColumns = {@JoinColumn(name = "emp_id")}, 
			inverseJoinColumns = {@JoinColumn(name = "comp_id")})
	List<Company> companies;

	//getters and setters
	//constructors

}

Company class

package com.javatrainingschool;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table (name = "company")
public class Company {
	
	@Id
	@GeneratedValue(strategy = GenerationType.AUTO)
	private int id;
	private String name;
	
	//getter and setters
	//constructors
}

Main testing class

package com.javatrainingschool;

import java.util.ArrayList;
import java.util.List;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.boot.Metadata;
import org.hibernate.boot.MetadataSources;
import org.hibernate.boot.registry.StandardServiceRegistry;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;

public class CompanyMainClass {
	
	public static void main(String[] args) {
		
		
		StandardServiceRegistry ssr = new StandardServiceRegistryBuilder().configure("hibernate.cfg.xml").build();  
	    Metadata meta = new MetadataSources(ssr).getMetadataBuilder().build();  
	      
	    SessionFactory factory = meta.getSessionFactoryBuilder().build();  
	    Session session = factory.openSession();  
	      
	    Transaction t = session.beginTransaction();    
	    
	    Company c1 = new Company();
	    c1.setName("Sopra");
	    
	    Company c2 = new Company();
	    c2.setName("TCS");
	    
	    Company c3 = new Company();
	    c3.setName("IBM");
	    
	    List<Company> companies = new ArrayList<Company>();
	    companies.add(c1);
	    companies.add(c3);
	    
	    List<Company> companies1 = new ArrayList<Company>();
	    companies1.add(c2);
	    companies1.add(c3);
	    
	    FreeLancerEmployee e = new FreeLancerEmployee();
	    e.setName("Kamal");
	    e.setAge(30);
	    e.setCompanies(companies);
	    
	    FreeLancerEmployee e1 = new FreeLancerEmployee();
	    e1.setName("Anjali");
	    e1.setAge(30);
	    e1.setCompanies(companies1);
	    
	    session.save(e);
	    session.save(e1);
	    
	    t.commit();
	    
	    System.out.println("The records have been saved successfully.");
	    
	    session.close();
	    factory.close();
	}
}

configuration file

<?xml version='1.0' encoding='UTF-8'?>  
<!DOCTYPE hibernate-configuration PUBLIC  
          "-//Hibernate/Hibernate Configuration DTD 3.0//EN"  
          "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">  
  
<hibernate-configuration>  
  
    <session-factory>  
        <property name="hbm2ddl.auto">update</property>  
        <property name="dialect">org.hibernate.dialect.MySQL8Dialect</property>  
        <property name="connection.url">jdbc:mysql://localhost:3306/employee_db</property>  
        <property name="connection.username">root</property>  
        <property name="connection.password">Kolkata12345</property>  
        <property name="connection.driver_class">com.mysql.jdbc.Driver</property>  
   		<!-- <mapping resource="player.hbm.xml"/>  -->
   		<mapping class = "com.javatrainingschool.FreeLancerEmployee"/>
   		<mapping class = "com.javatrainingschool.Company"/>
   	</session-factory>  
  
</hibernate-configuration>

Verify the tables in the database