Newsletter

Hibernate Many to Many Mapping Example

Let us see an example on this many to many relationship in hibernate.  Actually here there is no question of unidirectional, only Bi-Directional.

Applying many to many relationship between two pojo class objects is nothing but applying one to many relationship on both sides, which tends to Bi-Directional i mean many to many.

Example:

Let us see this, if we apply many to many association between two pojo class objects student and course, provided the relationship is one student may joined in multiple courses and one course contains lot of students (joined by multiple students)

Remember, when ever we are applying many to many relationship between two pojo class objects, on both sides  we need a collection property [As we are applying one to many from both the sides]

Note Points:

  • While applying many to many relationship between pojo classes,  a mediator table is mandatory in the database, to store primary key as foreign key both sides, we call this table as Join table
  • In many to many relationship join table contain foreign keys only

Many To Many Relationship Example

files required…..

  • Student.java
  • Course.java
  • Course.hbm.xml
  • Student.hbm.xml
  • OurLogic.java
  • hibernate.cfg.xml

Student.java

package str;

import java.util.Set;

public class Student {

	private int studentId;
	private String studentName;
	private int marks;

	private Set courses;

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

	public int getMarks() {
		return marks;
	}

	public void setMarks(int marks) {
		this.marks = marks;
	}

	public Set getCourses() {
		return courses;
	}

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

}

Course.java

package str;

import java.util.Set;

public class Course {

	private int courseId;
	private String courseName;
	private int duration;

	private Set students;

	public int getCourseId() {
		return courseId;
	}

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

	public String getCourseName() {
		return courseName;
	}

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

	public int getDuration() {
		return duration;
	}

	public void setDuration(int duration) {
		this.duration = duration;
	}

	public Set getStudents() {
		return students;
	}

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

}

Student.hbm.xml

<?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="str.Student" table="student">

<id name="studentId" column="studentid" />

<property name="studentName" column="studentname" length="20"/>
<property name="marks" />

<set name="courses" cascade="all" table="students_courses">

<key column="student_id "/>
<many-to-many class="str.Course" column="course_id" />

</set>

</class>

</hibernate-mapping>

Course.hbm.xml

<?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="str.Course" table="courses">

<id name="courseId" column="courseid" />

<property name="courseName" column="coursename" length="20"/>
<property name="duration" />

<set name="students" inverse="false" cascade="all" table="students_courses">

<key column="course_id" />
<many-to-many class="str.Student" column="student_id "/>

</set>

</class>

</hibernate-mapping>

OurLogic.java

package str;

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

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

public class OurLogic {

	public static void main(String args[])
	{

		Configuration cfg = new Configuration();
		cfg.configure("hibernate.cfg.xml"); 

		SessionFactory factory = cfg.buildSessionFactory();
		Session session = factory.openSession();		

		Student s1=new Student();
		s1.setStudentId(100);
		s1.setStudentName("James");
		s1.setMarks(98);

		Student s2=new Student();
		s2.setStudentId(101);
		s2.setStudentName("Lee");
		s2.setMarks(99);

		Course c1=new Course();
		c1.setCourseId(500);
		c1.setCourseName("Hibernate");
		c1.setDuration(7);

		Course c2=new Course();
		c2.setCourseId(501);
		c2.setCourseName("Java");
		c2.setDuration(30);

		Set s =new HashSet();
		      s.add(c1);
		      s.add(c2);

		s1.setCourses(s);
		s2.setCourses(s);

		    Transaction tx = session.beginTransaction();

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

		    tx.commit();

		    session.close();
		    System.out.println("Many To Many Bi-Directional is Done..!!");
		    factory.close();

	}
}

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>
<property name="connection.driver_class">oracle.jdbc.driver.OracleDriver
</property>
<property name="connection.url">jdbc:oracle:thin:@www.java4s.com:1521:XE</property>
<property name="connection.username">system</property>
<property name="connection.password">admin</property>

<property name="dialect">org.hibernate.dialect.OracleDialect</property>
<property name="show_sql">true</property>
<property name="hbm2ddl.auto">update</property>

<mapping resource="Student.hbm.xml"></mapping>
<mapping resource="Course.hbm.xml"></mapping>
</session-factory>
</hibernate-configuration>

Output

Just see the mapping files by seeing this output file….

​​

You Might Also Like

  ::. About the Author .::

Java4s_Author
- Java/J2EE Full Stack Developer
Founder of Java4s - Get It Yourself, A popular Java/J2EE Programming Blog, Love Java and UI frameworks.
You can sign-up for the Email Newsletter for your daily dose of Java tutorials.

Comments

14 Responses to “Hibernate Many to Many Mapping Example”
  1. hi jaca4s team ,
    i got this many-to-many concept clearly . thanks a lot .

  2. krish says:

    Super …..Excellent

  3. mahesh says:

    Hi Sivateja can u provide db tables syntax?

  4. sree says:

    Its too good to learn easilyy….

  5. can u provide oracle data base syntax along with the hibernate examples because we got some problems while creating the tables.

  6. Sasi says:

    Hi SivaTeja/Java4s Team,
    In Course.hbm.xml,pls explain why we used inverse=”false”.Anyway,it is a bidirectional relation,then why did we specify>Any specific purpose?

  7. Sir I’ve a doubt. Why are you using collection on both sides, Even it is not required to use collection in ‘Course.java’ because we are not using ‘setStudents()’ method. The same example is also explained here – http://www.dzone.com/tutorials/java/hibernate/hibernate-example/hibernate-mapping-many-to-many-1.html
    the example given in this link implement many to many relationship without using the collection in ‘Course.java’.
    Please sir help me out, I need more explanation.

  8. shrikanth reddy says:

    Superb i liked it…….

  9. praveen says:

    in course.hbm.xml you are applyied Inverse=false, what is that mean?

  10. arun says:

    How many tables we need to create while we using many to many?

  11. arun says:

    we have N no'of vendors and N no'of customers are there that time we need only two tables in this scenario can we use many to many relationship.

  12. Abhimanyu Moharana says:

    sir during mapping of respective primary keys like
    <id name="studentId" column="studentid"/> for student table and
    <id name="courseId" column="courseid" /> for course table ,
    it is showing exception that says courseid and studentid does not have defalt values.

    i min doubt that i have to change these parameters according to the class properties or database column name while mapping it to the 3rd table.

  13. Sagar Parkale says:

    If I don't want to use auto ddl commands in configuration file, I want to created tables manualy and then I want to store data from hibernate. What is the code for it, Please replay on parkale.sagar8@gmail.com

Name*
Mail*
Website



By posting your answer, you agree to our comments policy.
Most Recent Posts from Top Categories
Spring Boot Hibernate Spring
Contact | About Us | Privacy Policy | Advertise With Us

© 2010 - 2018 Java4s - Get It Yourself.
The content is copyrighted to Sivateja Kandula and may not be reproduced on other websites.