Hibernate 4 Many to Many Mapping using Annotation

In this section, you will learn how to do Many to Many Mapping of table in Hibernate using Annotation.

Hibernate 4 Many to Many Mapping using Annotation

Hibernate 4 Many to Many Mapping using Annotation

In this section, you will learn how to do Many to Many Mapping of table in Hibernate using Annotation.

In the below example, many to many mapping is done using three mysql table - student, course, student_course. In this example, the concept behind this mapping is - many students may have enroll for many courses and one course can be enrolled by many students.

EXAMPLE

The project hierarchy is given below :

The jar file used in the example is given below:

The query used to create the database table is given below :

CREATE TABLE `student` ( 
`student_id` bigint(10) NOT NULL auto_increment, 
`student_name` varchar(50) default NULL, 
PRIMARY KEY (`student_id`) 
) ENGINE=InnoDB DEFAULT CHARSET=latin1


CREATE TABLE `course` ( 
`course_id` bigint(10) NOT NULL auto_increment, 
`course_name` varchar(50) default NULL, 
PRIMARY KEY (`course_id`) 
) ENGINE=InnoDB DEFAULT CHARSET=latin1


CREATE TABLE `student_course` (                                                           
  `student_id` bigint(10) NOT NULL,                                                       
  `course_id` bigint(10) NOT NULL,                                                        
  PRIMARY KEY  (`student_id`,`course_id`),                                                
  KEY `FK_course` (`course_id`),                                                          
  CONSTRAINT `FK_course` FOREIGN KEY (`course_id`) REFERENCES `course` (`course_id`),     
  CONSTRAINT `FK_student` FOREIGN KEY (`student_id`) REFERENCES `student` (`student_id`)  
) ENGINE=InnoDB DEFAULT CHARSET=latin1 

CODE

hibernate.cfg.xml ( /src/hibernate.cfg.xml )

<?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>
<!-- Database connection settings -->
<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="connection.url">jdbc:mysql://192.168.10.13:3306/anky</property>
<property name="connection.username">root</property>
<property name="connection.password">root</property>

<property name="connection.pool_size">1</property>
<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="current_session_context_class">thread</property>
<property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property>
<property name="show_sql">true</property>
<property name="hbm2ddl.auto">validate</property>

<mapping class="net.roseindia.Student" />
<mapping class="net.roseindia.Course" />

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

Student.java ( /src/net/roseindia/Student.java )

package net.roseindia;

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

import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
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
@Column(name="student_id")
@GeneratedValue
private Long studentId;

@Column(name="student_name")
private String studentName ;

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

public Student() {
}

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;
}

@ManyToMany(cascade = {CascadeType.ALL})
@JoinTable(name="student_course",joinColumns={@JoinColumn(name="student_id")},inverseJoinColumns={@JoinColumn(name="course_id")})
private Set<Course> courses = new HashSet<Course>();

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

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

Course.java ( /src/net/roseindia/Course.java )

package net.roseindia;

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

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.ManyToMany;
import javax.persistence.Table;

@Entity
@Table(name = "course")
public class Course {
@Id
@Column(name = "course_id")
@GeneratedValue
private Long courseId;

@Column(name = "course_name")
private String courseName;

@ManyToMany(mappedBy="courses")
private Set<Student> students = new HashSet<Student>();

public Course() {
}

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

public Set<Student> getStudents() {
return students;
}

public void setStudents(Set<Student> students) {
this.students = students;
}

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;
}
}

ManageStudent.java ( /src/net/roseindia/ManageStudent.java )

package net.roseindia;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.ServiceRegistryBuilder;

public class ManageStudent {
private static SessionFactory sf;
private static ServiceRegistry serviceRegistry;

@SuppressWarnings("unchecked")
public static void main(String[] args) {
try {
Configuration configuration = new Configuration();
configuration.configure();
serviceRegistry = new ServiceRegistryBuilder().applySettings(
configuration.getProperties()).buildServiceRegistry();
sf = configuration.buildSessionFactory(serviceRegistry);
} catch (Throwable ex) {
System.err.println("Failed to create sessionFactory object." + ex);
throw new ExceptionInInitializerError(ex);
}


System.out.println("Hibernate Many to Many Mapping Example Using Annotation ");

Session session = sf.openSession();
session.beginTransaction();

Course c1=new Course("Cryptography");
Course c2=new Course("Java");

Student s1=new Student("Sachin Bharadwaj");
Student s2=new Student("Vikas Sharma");

s1.getCourses().add(c1);
s1.getCourses().add(c2);
s2.getCourses().add(c2);

session.save(s1);
session.save(s2);

session.getTransaction().commit();
session.close();
}
}

OUTPUT

After execution, you will get the following output in console :

Hibernate Many to Many Mapping Example Using Annotation 
Hibernate: insert into student (student_name) values (?)
Hibernate: insert into course (course_name) values (?)
Hibernate: insert into course (course_name) values (?)
Hibernate: insert into student (student_name) values (?)
Hibernate: insert into student_course (student_id, course_id) values (?, ?)
Hibernate: insert into student_course (student_id, course_id) values (?, ?)
Hibernate: insert into student_course (student_id, course_id) values (?, ?)

In the student table, you should get the following record :

In the course table, you should get the following record :

In the student_course table, you should get the following record :

Download Source Code