
How does many to many relationship work in Hibernate?

In many to mant relationship each row in table A linked to multiple rows in table B and vice versa.Here is an example of Student and course. one student can chose multiple subject in the same way 1 course can be assigned to multiple student.
Configuration file : hibernate.cfg.xml
<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/hibernaterelationship</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password">root</property>
<property name="hibernate.connection.pool_size">10</property>
<property name="show_sql">true</property>
<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="hibernate.hbm2ddl.auto">create-drop</property>
<!-- Mapping files -->
<mapping class="net.roseindia.table.Course" />
<mapping class="net.roseindia.table.Student" />
</session-factory>
</hibernate-configuration>
Table classes :
Course.java
package net.roseindia.table;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name = "course")
public class Course {
private int courseId;
private String courseName;
public Course(String course) {
// TODO Auto-generated constructor stub
this.courseName=course;
}
@Id
@GeneratedValue
@Column(name = "courseId", nullable = false)
public int getCourseId() {
return courseId;
}
public void setCourseId(int courseId) {
this.courseId = courseId;
}
@Column(name = "courseName", nullable = false)
public String getCourseName() {
return courseName;
}
public void setCourseName(String courseName) {
this.courseName = courseName;
}
}
Student.java
package net.roseindia.table;
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.ManyToMany;
import javax.persistence.Table;
@Entity
@Table(name="student")
public class Student {
private int id;
private String name;
private Set<Course> courses = new HashSet<Course>();
public Student(String name) {
// TODO Auto-generated constructor stub
this.name = name;
}
public Student(String name, Set<Course> courses) {
this.name = name;
this.courses = courses;
}
@Id
@GeneratedValue
@Column(name = "studentId", nullable = false)
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
@Column(name = "studentName", nullable = false)
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@ManyToMany(cascade=CascadeType.ALL)
public Set<Course> getCourses() {
return courses;
}
public void setCourses(Set<Course> courses) {
this.courses = courses;
}
}

Continued..
Util Class:HibernateUtil.java
package net.roseindia.util;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.AnnotationConfiguration;
public class HibernateUtil {
private static SessionFactory sessionFactory = null;
static {
sessionFactory = new AnnotationConfiguration().configure()
.buildSessionFactory();
}
public static SessionFactory getseSessionFactory() {
return sessionFactory;
}
}
Main Class : ManyToMany.java
package net.roseindia.application;
import java.util.HashSet;
import java.util.Set;
import net.roseindia.table.Course;
import net.roseindia.table.Student;
import net.roseindia.util.HibernateUtil;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
public class ManyToMany{
public static void main(String[] args){
Session session=HibernateUtil.getseSessionFactory().openSession();
Transaction transaction=null;
try{
transaction=session.beginTransaction();
Set<Course> courses=new HashSet<Course>();
courses.add(new Course("Maths"));
courses.add(new Course("Science"));
Student student1=new Student("Ron", courses);
Student student2=new Student("Ric",courses);
session.save(student1);
session.save(student2);
transaction.commit();
}catch(HibernateException he){
System.out.println(he.getMessage());
}
finally{
session.close();
}
}
}
Output:
Hibernate: insert into student (studentName) values (?) Hibernate: insert into course (courseName) values (?) Hibernate: insert into course (courseName) values (?) Hibernate: insert into student (studentName) values (?) Hibernate: insert into student_course (student_studentId, courses_courseId) values (?, ?) Hibernate: insert into student_course (student_studentId, courses_courseId) values (?, ?) Hibernate: insert into student_course (student_studentId, courses_courseId) values (?, ?) Hibernate: insert into student_course (student_studentId, courses_courseId) values (?, ?)

see this simple annotation example
If you are facing any programming issue, such as compilation errors or not able to find the code you are looking for.
Ask your questions, our development team will try to give answers to your questions.