SQL Zone is brought to you in partnership with:

Meyyappan has posted 101 posts at DZone. View Full User Profile

Hibernate Many-To-Many Mapping Tutorial

06.14.2012
| 115403 views |
  • submit to reddit

In this example you will learn how to map many-to-many relationship using Hibernate. Consider the following relationship between Student and Course entity.

 

According to the relationship a student can enroll in any number of courses and the course can have any number of students.

To create this relationship you need to have a STUDENT, COURSE and STUDENT_COURSE table. The relational model is shown below.

To create the STUDENT and COURSE tables you need to create the following hibernate mapping files.

Student.hbm.xml is used to create the STUDENT and STUDENT_COURSE table.

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
    <class name="com.vaannila.student.Student" table="STUDENT">
        <meta attribute="class-description">This class contains student details.</meta>
        <id name="studentId" type="long" column="STUDENT_ID">
            <generator class="native" />
        </id>
        <property name="studentName" type="string" length="100" not-null="true" column="STUDENT_NAME" />
        <set name="courses" table="STUDENT_COURSE" cascade="all">
            <key column="STUDENT_ID" />
            <many-to-many column="COURSE_ID"  class="com.vaannila.student.Course" />
        </set>
    </class>
</hibernate-mapping>

We use many-to-many element to create the many-to-many relationship between the Student and Course entities. Since a student can enroll in any number of courses we use a collection to hold the values. In this case we use Set.

Course.hbm.xml is used to create the COURSE table.

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
	"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
	"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="com.vaannila.student.Course" table="COURSE">
	<meta attribute="class-description">
		This class contains course details.
	</meta>
	<id name="courseId" type="long" column="COURSE_ID">
		<generator class="native"/>
	</id>
	<property name="courseName" type="string" column="COURSE_NAME"/>	
</class>
</hibernate-mapping>

Now create the hibernate configuration file and add all the mapping files.

<?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="hibernate.connection.driver_class"> org.hsqldb.jdbcDriver</property>
        <property name="hibernate.connection.url"> jdbc:hsqldb:hsql://localhost</property>
        <property name="hibernate.connection.username">sa</property>
        <property name="connection.password"></property>
        <property name="connection.pool_size">1</property>
        <property name="hibernate.dialect"> org.hibernate.dialect.HSQLDialect</property>
        <property name="show_sql">true</property>
        <property name="hbm2ddl.auto">create-drop</property>
        <mapping resource="com/vaannila/student/Student.hbm.xml"/>
        <mapping resource="com/vaannila/student/Course.hbm.xml"/>
    </session-factory>
</hibernate-configuration>

After creating the configuration file, generate java class files using Hibernate Tools.(To generate code using Hibernate Tools refer this example )

The following classes will be generated.

package com.vaannila.student;

// Generated May 30, 2009 6:48:40 AM by Hibernate Tools 3.2.4.GA

import java.util.HashSet;
import java.util.Set;

/**
 * This class contains the student details.
 */
public class Student implements java.io.Serializable {

	private long studentId;
	private String studentName;
	private Set<Course> courses = new HashSet<Course>(0);

	public Student() {
	}

	public Student(String studentName) {
		this.studentName = studentName;
	}

	public Student(String studentName, Set<Course> courses) {
		this.studentName = studentName;
		this.courses = courses;
	}

	public long getStudentId() {
		return this.studentId;
	}

	public void setStudentId(long studentId) {
		this.studentId = studentId;
	}

	public String getStudentName() {
		return this.studentName;
	}

	public void setStudentName(String studentName) {
		this.studentName = studentName;
	}

	public Set<Course> getCourses() {
		return this.courses;
	}

	public void setCourses(Set<Course> courses) {
		this.courses = courses;
	}

}
package com.vaannila.student;

// Generated May 30, 2009 6:48:40 AM by Hibernate Tools 3.2.4.GA

/**
 * 	This class contains the course details.
 * 	
 */
public class Course implements java.io.Serializable {

	private long courseId;
	private String courseName;

	public Course() {
	}

	public Course(String courseName) {
		this.courseName = courseName;
	}

	public long getCourseId() {
		return this.courseId;
	}

	public void setCourseId(long courseId) {
		this.courseId = courseId;
	}

	public String getCourseName() {
		return this.courseName;
	}

	public void setCourseName(String courseName) {
		this.courseName = courseName;
	}

}
package com.vaannila.student;

import java.util.HashSet;
import java.util.Set;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.Transaction;

import com.vaannila.util.HibernateUtil;

public class Main {

	public static void main(String[] args) {

		Session session = HibernateUtil.getSessionFactory().openSession();
		Transaction transaction = null;
		try {
			transaction = session.beginTransaction();

			Set<Course> courses = new HashSet<Course>();
			courses.add(new Course("Maths"));
			courses.add(new Course("Computer Science"));

			Student student1 = new Student("Eswar", courses);
			Student student2 = new Student("Joe", courses);
			session.save(student1);
			session.save(student2);

			transaction.commit();
		} catch (HibernateException e) {
			transaction.rollback();
			e.printStackTrace();
		} finally {
			session.close();
		}

	}
}

Create the Main class to run the example.

package com.vaannila.student;

import java.util.HashSet;
import java.util.Set;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.Transaction;

import com.vaannila.util.HibernateUtil;

public class Main {

	public static void main(String[] args) {

		Session session = HibernateUtil.getSessionFactory().openSession();
		Transaction transaction = null;
		try {
			transaction = session.beginTransaction();

			Set<Course> courses = new HashSet<Course>();
			courses.add(new Course("Maths"));
			courses.add(new Course("Computer Science"));

			Student student1 = new Student("Eswar", courses);
			Student student2 = new Student("Joe", courses);
			session.save(student1);
			session.save(student2);

			transaction.commit();
		} catch (HibernateException e) {
			transaction.rollback();
			e.printStackTrace();
		} finally {
			session.close();
		}

	}
}

On executing the Main class you will see the following output.

The STUDENT table has two records.

The COURSE table has two records.

The STUDENT_COURSE table has four records to link the student and courses.

Each student has enrolled in the same two courses, this illustrates the many-to-many mapping.

The folder structure of the example is shown below.

You can download the source code of this example here.

Source : Download
Published at DZone with permission of its author, Meyyappan Muthuraman.

(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)

Tags:

Comments

Ho Ngoc Tan replied on Tue, 2012/12/25 - 4:08am

 Thanks for nice tutorial.

You can upload the lib( jar files) please !

--Tu rack --

Divya Jeganathan replied on Sun, 2014/02/09 - 11:01am

This blog was very useful to understand. I am a fresher i saw a Freshers Jobs  in Jobsdhost.com  and attended an interview their they asked this question.

Omar Ahmed replied on Sat, 2014/07/12 - 1:02pm

 Thanks for nice tutorial.

العاب تلبيس

Comment viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.