Hibernate Many-to-Many

Many-to-Many relationship in real world:

Two items are said to be in Many-to-Many relationship if many occurrence of item are belong to the many occurrences of other item and vice versa. E.g. Many student – Many subject.

Many-to-Many relationship in programming:

Two entities are said to be in Many-to-Many relationship if many occurrence of entity belongs to many occurrence of other entity and vice versa.

Example:

Student.java

import java.util.Set;
 
/**
 * This class represents a persistent class for Student.
 * @author w3schools
 */
public class Student {
	//data members
	private int studentId;
	private String firstName;
	private String lastName;
	private String className;
	private String rollNo;
	private int age;
	private Set subjects;
 
	//no-argument constructor
	public Student(){
 
	}
 
	//argument constructor
	public Student(String firstName, String lastName, 
			String className, String rollNo, int age){
		this.firstName = firstName;
		this.lastName = lastName;
		this.className = className;
		this.rollNo = rollNo;
		this.age = age;		
	}
 
	//getter and setter methods
	public int getStudentId() {
		return studentId;
	}
	public void setStudentId(int studentId) {
		this.studentId = studentId;
	}
	public String getFirstName() {
		return firstName;
	}
	public void setFirstName(String firstName) {
		this.firstName = firstName;
	}
	public String getLastName() {
		return lastName;
	}
	public void setLastName(String lastName) {
		this.lastName = lastName;
	}
	public String getClassName() {
		return className;
	}
	public void setClassName(String className) {
		this.className = className;
	}
	public String getRollNo() {
		return rollNo;
	}
	public void setRollNo(String rollNo) {
		this.rollNo = rollNo;
	}
	public int getAge() {
		return age;
	}
	public void setAge(int age) {
		this.age = age;
	}
	public Set getSubjects() {
		return subjects;
	}
	public void setSubjects(Set subjects) {
		this.subjects = subjects;
	}
 
}

Subject.java

/**
 * This class represents a persistent class for Subject.
 * @author w3schools
 */
public class Subject {
	//data members
	private int subjectId;
	private String subjectName;
 
	//no argument constructor
	public Subject(){
 
	}
 
	//argument constructor
	public Subject(String subjectName){
		this.subjectName = subjectName;
	}
 
	//getter and setter methods
	public int getSubjectId() {
		return subjectId;
	}
	public void setSubjectId(int subjectId) {
		this.subjectId = subjectId;
	}
	public String getSubjectName() {
		return subjectName;
	}
	public void setSubjectName(String subjectName) {
		this.subjectName = subjectName;
	}	
 
	public boolean equals(Object obj) {
                    if (obj == null){
    	            return false;
                    }
                    if (!this.getClass().equals(obj.getClass())){
    	             return false;
                    }
                    Subject obj2 = (Subject)obj;
                    if((this.subjectId == obj2.getSubjectId()) && 
    		  (this.subjectName.equals(obj2.getSubjectName()))){
                           return true;
                    }
                    return false;
                }
 
              public int hashCode() {
                    int tmp = 0;
                    tmp = ( subjectId + subjectName).hashCode();
                    return tmp;
              }
}

hibernate.cfg.xml

<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE hibernate-configuration SYSTEM
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
 
<hibernate-configuration>
 
    <session-factory>
        <property name="dialect">
           org.hibernate.dialect.OracleDialect
        </property>
        <property name="connection.url">
           jdbc:oracle:thin:@localhost:1521:XE
        </property>
        <property name="connection.username">
           system
        </property>
        <property name="connection.password">
           oracle
        </property>
        <property name="connection.driver_class">
           oracle.jdbc.driver.OracleDriver
        </property>
        <property name="hbm2ddl.auto">
           update
        </property>
        <property name="show_sql">
           true
        </property>
 
        <mapping resource="student.hbm.xml"/>
        <mapping resource="subject.hbm.xml"/>
 
    </session-factory>
 
</hibernate-configuration>

student.hbm.xml

<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE hibernate-mapping SYSTEM
    "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
 
<hibernate-mapping>
 
 <class name="com.w3schools.business.Student" table="Student">
  <id name="studentId" type="int" column="Student_Id">
	<generator class="native"></generator>
  </id>
 
  <property name="firstName" column="First_Name" type="string"/>
  <property name="lastName" column="Last_Name" type="string"/>
  <property name="className" column="Class" type="string"/>
  <property name="rollNo" column="RollNo" type="string"/>
  <property name="age" column="Age" type="int"/>
 
  <set name="subjects" cascade="all">
    <key column="Student_Id"/>
    <many-to-many class="com.w3schools.business.Subject"/>
  </set>
 
 </class>
 
</hibernate-mapping>

subject.hbm.xml

<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE hibernate-mapping SYSTEM
    "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
 
<hibernate-mapping>
 
  <class name="com.w3schools.business.Subject" table="Subject">
    <id name="subjectId" type="int" column="Subject_Id">
	<generator class="native"></generator>
    </id>
 
    <property name="subjectName" column="Subject_Name"
                                        type="string"></property>
 
  </class>
 
</hibernate-mapping>

HibernateUtil.java

import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
 
/**
 * This is a utility class for getting the hibernate session object.
 * @author w3schools
 */
public class HibernateUtil {
    private static final SessionFactory sessionFactory = 
                                           buildSessionFactory();
 
    private static SessionFactory buildSessionFactory() {
    	SessionFactory sessionFactory = null;
        try {
        	//Create the configuration object.
        	Configuration configuration = new Configuration(); 
        	//Initialize the configuration object 
                //with the configuration file data
        	configuration.configure("hibernate.cfg.xml");
        	// Get the SessionFactory object from configuration.
        	sessionFactory = configuration.buildSessionFactory();
        }
        catch (Exception e) {
           e.printStackTrace();
        }
        return sessionFactory;
    }
 
    public static SessionFactory getSessionFactory() {
        return sessionFactory;
    }
 
}

HibernateTest.java

import java.util.HashSet;
import com.w3schools.persistence.StudentDBOperations;
 
/**
 * This class is used for the hibernate operations.
 * @author w3schools
 */
public class HibernateTest {
	public static void main(String args[]){
		HashSet subjectSet1 = new HashSet();
		subjectSet1.add(new Subject("Data Structure"));
		subjectSet1.add(new Subject("Operting System"));
 
		HashSet subjectSet2 = new HashSet();
		subjectSet2.add(new Subject("Compier"));
		subjectSet2.add(new Subject("Networking"));
		subjectSet2.add(new Subject("DBMS"));
 
		//Create the student object.
		Student student1 = new Student("Shveta", "Gogia", 
				"MCA final", "MCA/07/72", 27);	
		Student student2 = new Student("Bharti", "Grover", 
				"MCA final", "MCA/07/73", 32);	
 
		student1.setSubjects(subjectSet1);
		student2.setSubjects(subjectSet2);
 
		StudentDBOperations obj = new StudentDBOperations();
		//insert student object.
		obj.addStudent(student1);
		obj.addStudent(student2);
 
		//show all student object.
		obj.showAllStudentDetails();
 
	}
}

StudentDBOperations.java

import java.util.List;
import java.util.Set;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.Transaction;
import com.w3schools.business.Student;
import com.w3schools.business.Subject;
 
/**
 * This class contains the methods to interact with database.
 * @author w3schools
 */
public class StudentDBOperations {
	/**
	 * This method is used to insert a new student record.
	 * @param student
	 * @return studentId
	 * @author w3schools
	 */
	public Integer addStudent(Student student){
		Transaction tx = null;
	    Integer studentId = null;
	    //Get the session object.
	    Session session = 
                 HibernateUtil.getSessionFactory().openSession();
	    try{
	         tx = session.beginTransaction();
	         studentId = (Integer) session.save(student); 
	         tx.commit();
	      }catch (HibernateException e) {
	         if(tx!=null){
	        	 tx.rollback();
	         }
	         e.printStackTrace(); 
	      }finally {
	         session.close(); 
	      }
	      return studentId;	
	}
 
	/**
	 * This method is used retrieve and show the records.
	 * @author w3schools
	 */
	public void showAllStudentDetails(){
	    Transaction tx = null;
	    //Get the session object.
	    Session session = 
                    HibernateUtil.getSessionFactory().openSession();
	    try{
	         tx = session.beginTransaction();
	         List<Student> students = 
                         session.createQuery("FROM Student").list();
	         for(Student student : students){
	        	 System.out.println("First Name: " 
                                           + student.getFirstName()); 
	        	 System.out.println("Last Name: " 
                                            + student.getLastName()); 
	        	 System.out.println("Class: " 
                                           + student.getClassName()); 
	        	 System.out.println("RollNo: " 
                                              + student.getRollNo()); 
	        	 System.out.println("Age: "
                                                 + student.getAge()); 
	        	 Set<Subject> subjects = student.getSubjects();
	        	 for(Subject subject : subjects){
	        		 System.out.println("Subject Name:" 
                                            + subject.getSubjectName());
	        	 }
	         }
	         tx.commit();
	      }catch (HibernateException e) {
	         if(tx!=null){
	        	 tx.rollback();
	         }
	         e.printStackTrace(); 
	      }finally {
	         session.close(); 
	      }
	}
}

Output:

Hibernate: select hibernate_sequence.nextval from dual
Hibernate: select hibernate_sequence.nextval from dual
Hibernate: select hibernate_sequence.nextval from dual
Hibernate: insert into Student (First_Name, Last_Name, Class, 
RollNo, Age, Student_Id) values (?, ?, ?, ?, ?, ?)
Hibernate: insert into Subject (Subject_Name, Subject_Id) values (?, ?)
Hibernate: insert into Subject (Subject_Name, Subject_Id) values (?, ?)
Hibernate: insert into subjects (Student_Id, elt) values (?, ?)
Hibernate: insert into subjects (Student_Id, elt) values (?, ?)
Hibernate: select hibernate_sequence.nextval from dual
Hibernate: select hibernate_sequence.nextval from dual
Hibernate: select hibernate_sequence.nextval from dual
Hibernate: select hibernate_sequence.nextval from dual
Hibernate: insert into Student (First_Name, Last_Name, Class, 
RollNo, Age, Student_Id) values (?, ?, ?, ?, ?, ?)
Hibernate: insert into Subject (Subject_Name, Subject_Id) values (?, ?)
Hibernate: insert into Subject (Subject_Name, Subject_Id) values (?, ?)
Hibernate: insert into Subject (Subject_Name, Subject_Id) values (?, ?)
Hibernate: insert into subjects (Student_Id, elt) values (?, ?)
Hibernate: insert into subjects (Student_Id, elt) values (?, ?)
Hibernate: insert into subjects (Student_Id, elt) values (?, ?)
Hibernate: select student0_.Student_Id as Student1_0_, 
student0_.First_Name as First2_0_, student0_.Last_Name as 
Last3_0_, student0_.Class as Class0_, student0_.RollNo as 
RollNo0_, student0_.Age as Age0_ from Student student0_
First Name: Shveta
Last Name: Gogia
Class: MCA final
RollNo: MCA/07/72
Age: 27
Hibernate: select subjects0_.Student_Id as Student1_1_, 
subjects0_.elt as elt1_, subject1_.Subject_Id as Subject1_2_0_, 
subject1_.Subject_Name as Subject2_2_0_ from subjects
 subjects0_, Subject subject1_ where
 subjects0_.elt=subject1_.Subject_Id(+) and subjects0_.Student_Id=?
Subject Name:Operting System
Subject Name:Data Structure
First Name: Bharti
Last Name: Grover
Class: MCA final
RollNo: MCA/07/73
Age: 32
Hibernate: select subjects0_.Student_Id as Student1_1_, 
subjects0_.elt as elt1_, subject1_.Subject_Id as Subject1_2_0_,
 subject1_.Subject_Name as Subject2_2_0_ from subjects 
subjects0_, Subject subject1_ where
 subjects0_.elt=subject1_.Subject_Id(+) and subjects0_.Student_Id=?
Subject Name:Compier
Subject Name:DBMS
Subject Name:Networking

Download this example.