Hibernate – Many to Many Mapping

In this example I will show how to map many-to-many relationship using Annotations.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 ENROLLMENT table. The relational model is shown below.

To create the STUDENT, COURSE and ENROLLMENT table you need to create the following Java Class files.

Student.java

package com.hibernate.manytomanymapping;

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

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
import javax.persistence.Table;

@Entity
@Table(name="STUDENT")
public class Student {
	
	@Id
	@GeneratedValue
	@Column(name="STUDENT_ID")
	private long studentId;
	
	@Column(name="STUDENT_NAME")
	private String studentName;
	
	@ManyToMany(fetch=FetchType.LAZY)
	@JoinTable(name="ENROLLMENT", 
		joinColumns={@JoinColumn(name="STUDENT_ID")}, 
		inverseJoinColumns={@JoinColumn(name="COURSE_ID")})
	private List<Course> courses = new ArrayList<Course>();
	
	public long getStudentId() {
		return studentId;
	}
	
	public void setStudentId(long studentId) {
		this.studentId = studentId;
	}
	
	public String getStudentName() {
		return studentName;
	}
	
	public void setStudentName(String studentName) {
		this.studentName = studentName;
	}
	
	public List<Course> getCourses() {
		return courses;
	}
	
	public void setCourse(List<Course> courses) {
		this.courses = courses;
	}

}

A Student is linked to a Course through a association table named ENROLLMENT ; this association table has a foreign key column named COURSE_ID pointing to the COURSE table (materialized by the inverseJoinColumn, and a foreign key column named STUDENT_ID pointing to the STUDENT table materialized by the joinColumns attribute.
You must declare the join table name and the join columns explicitly in such a mapping.

Course.java

package com.hibernate.manytomanymapping;

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

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
import javax.persistence.Table;

@Entity
@Table(name="COURSE")
public class Course {
	
	@Id
	@GeneratedValue
	@Column(name="COURSE_ID")
	private long courseId;
	
	@Column(name="COURSE_NAME")
	private String courseName;
	
	@ManyToMany(fetch=FetchType.LAZY)
	@JoinTable(name="ENROLLMENT", 
		joinColumns={@JoinColumn(name="COURSE_ID")}, 
		inverseJoinColumns={@JoinColumn(name="STUDENT_ID")})
	private List<Student> students = new ArrayList<Student>();

	public long getCourseId() {
		return courseId;
	}
	
	public void setCourseId(long courseId) {
		this.courseId = courseId;
	}
	
	public String getCourseName() {
		return courseName;
	}
	
	public void setCourseName(String courseName) {
		this.courseName = courseName;
	}
	
	public List<Student> getStudents() {
		return students;
	}
	
	public void setStudents(List<Student> students) {
		this.students = students;
	}

}

A Course is linked to a Student through a association table named ENROLLMENT ; this association table has a foreign key column named STUDENT_ID pointing to the STUDENT table (materialized by the inverseJoinColumn, and a foreign key column named COURSE_ID pointing to the COURSE table materialized by the joinColumns attribute.
You must declare the join table name and the join columns explicitly in such a mapping.

Main.java

package com.hibernate.manytomanymapping;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;

public class Main {

	public static void main(String[] args) {
		Configuration config = new Configuration();
		config.addAnnotatedClass(Student.class);
		config.addAnnotatedClass(Course.class);
		config.configure("hibernate.cfg.xml");
		
		SessionFactory factory = config.buildSessionFactory();
		Session session = factory.getCurrentSession();
		Transaction transaction =  session.beginTransaction();
		
		Student student1 = new Student();
		student1.setStudentName("Alex Rod");
		
		Student student2 = new Student();
		student2.setStudentName("Linda Barry");
		
		Student student3 = new Student();
		student3.setStudentName("John Doe");
		
		Student student4 = new Student();
		student4.setStudentName("James Dean");
		
		Course java101 = new Course();
		java101.setCourseName("Java - 101");
		
		Course cplus101 = new Course();
		cplus101.setCourseName("C++ - 101");
		
		Course math101 = new Course();
		math101.setCourseName("Math - 101");
		
		java101.getStudents().add(student1);
		java101.getStudents().add(student2);
		java101.getStudents().add(student3);
		cplus101.getStudents().add(student2);
		cplus101.getStudents().add(student3);
		math101.getStudents().add(student4);
		
		session.save(student1);
		session.save(student2);
		session.save(student3);
		session.save(student4);
		session.save(java101);
		session.save(cplus101);
		session.save(math101);
		
		transaction.commit();
	}

}

On executing the Main class you will see the following output.
The STUDENT table

The COURSE table

The ENROLLMENT table to link the student and courses.

Many to Many Relationship

Advertisements

About kaanmutlu

Software Developer - Computer Engineer from Istanbul, Turkey
This entry was posted in Uncategorized and tagged , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s