Home  >  Hibernate

Example of @ManyToMany in Hibernate

By Arvind Rai, May 20, 2013
@ManyToMany in hibernate, creates the association between the entities in such a way that many entities can be associated with many entities. It will be clearer by example. More than one student is associated with more than one teacher and vice-versa. To achieve Many-To-Many association below annotation are used.
@ManyToMany(
   targetEntity=Student.class,
   cascade=CascadeType.ALL
)
 
Here targetEntity is the entity which will be fetched in the current entity. @ManyToMany takes the help of third table which is achieved by @JoinTable as giver below.
 @JoinTable(
    name="teacher_student",
   joinColumns=@JoinColumn(name="teacher_id"),
   inverseJoinColumns=@JoinColumn(name="student_id")
)
Here joinColumns and inverseJoinColumns define the column names of third table. joinColumns defines column for current entity and inverseJoinColumns defines the column for second entity.
Find the below example of teacher and student Many-to-many association.

Many-to-many Table Association

Example of @ManyToMany in Hibernate

Find the example now.

Teacher.java
package com.concretepage.persistence;
import java.io.Serializable;
import java.util.Set;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
import javax.persistence.Table;
@Entity
@Table(name="teacher")
public class Teacher implements Serializable {
	private static final long serialVersionUID = 1L;
	@Id
	@Column(name="teacher_id")
	private int teacherId;
	
	@Column(name="teacher_name")
	private String teacherName;
	
	@ManyToMany(
	        targetEntity=Student.class,
	        cascade=CascadeType.ALL
	)
        @JoinTable(
          name="teacher_student",
          joinColumns=@JoinColumn(name="teacher_id"),
          inverseJoinColumns=@JoinColumn(name="student_id")
        )
	private Set<Student> students;
	
	public Teacher(int teacherId,String teacherName,Set<Student> students){
		this.teacherId=teacherId;
		this.teacherName=teacherName;
		this.students=students;
	}
	public Teacher(int teacherId,String teacherName){}
	public String getTeacherName() {
		return teacherName;
	}
	public void setTeacherName(String teacherName) {
		this.teacherName = teacherName;
	}
	public Set<Student> getStudents() {
		return students;
	}
	public void setStudents(Set<Student> students) {
		this.students = students;
	}
	public int getTeacherId() {
		return teacherId;
	}
	public void setTeacherId(int teacherId) {
		this.teacherId = teacherId;
	}
}
 


Student.java
package com.concretepage.persistence;
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name="student")
public class Student implements Serializable {
	private static final long serialVersionUID = 1L;
	@Id
	@Column(name="student_id")
	private int studentId;
	
	@Column(name="student_name")
	private String studentName;
	
	public Student(int studentId,String studentName){
		this.studentId=studentId;
		this.studentName=studentName;
	}
	public int getStudentId() {
		return studentId;
	}
	public void setStudentId(int studentId) {
		this.studentId = studentId;
	}
	public String getStudentName() {
		return studentName;
	}
	public void setStudentName(String studentName) {
		this.studentName = studentName;
	}
}
 


HibernateUtil.java
package com.concretepage.util;
import java.util.HashSet;
import java.util.Properties;
import java.util.Set;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.AnnotationConfiguration;
import com.concretepage.persistence.College;
import com.concretepage.persistence.Student;
import com.concretepage.persistence.Teacher;
public class HibernateUtil {
	private static final SessionFactory concreteSessionFactory;
		static {
		 try {
				Properties prop= new Properties();
				prop.setProperty("hibernate.connection.url", "jdbc:mysql://localhost:3306/hibernate");
				prop.setProperty("hibernate.connection.username", "root");
				prop.setProperty("hibernate.connection.password", "");
				prop.setProperty("hibernate.hbm2ddl.auto", "update");
				prop.setProperty("dialect", "org.hibernate.dialect.MySQLDialect");
				
				concreteSessionFactory = new AnnotationConfiguration()
			   .addPackage("com.concretepage.persistence")
					   .addProperties(prop)
					   .addAnnotatedClass(Teacher.class)
					   .addAnnotatedClass(Student.class)
					   .buildSessionFactory();
		  } catch (Throwable ex) {
			throw new ExceptionInInitializerError(ex);
		  }
		}
		public static Session getSession()
				throws HibernateException {
			return concreteSessionFactory.openSession();
		}
		public static void main(String... args){
			Session session=getSession();
	    	session.beginTransaction();
	    	Student s1=new Student(1,"Ram");
	    	Student s2=new Student(2,"Shyam");
	    	Set<Student> s=new HashSet<Student>();
	    	s.add(s1);
	    	s.add(s2);
	    	Teacher t=new Teacher(1,"Ramesh",s);
	    	session.persist(t);
	       	session.getTransaction().commit();
	   }
	}
 
Output

Example of @ManyToMany in Hibernate
POSTED BY
ARVIND RAI
ARVIND RAI
FIND MORE TUTORILAS


©2018 concretepage.com | Privacy Policy | Contact Us