top of page
index-1-1.jpg

Many To Many Relationship Using XML

This article is about how to write many to many relationship using XML in hibernate. Many to many means that we can have many rows in one table against many rows in another table. In my previous article I created simple application in hibernate using XML. Here is an example with a many-to-many relationship: A student can enroll to many courses and a course can be enrolled by many students.

Step 1. Create Student and Courses table

-- Table: student

-- DROP TABLE student;

CREATE TABLE student
(
  id integer NOT NULL,
  name character varying,
  CONSTRAINT student_pkey PRIMARY KEY (id )
)
WITH (
  OIDS=FALSE
);
ALTER TABLE student
  OWNER TO postgres;

-- Table: course

-- DROP TABLE course;

CREATE TABLE course
(
  id integer NOT NULL,
  name character varying,
  CONSTRAINT course_pkey PRIMARY KEY (id )
)
WITH (
  OIDS=FALSE
);
ALTER TABLE course
  OWNER TO postgres;

-- Table: student_course_map

-- DROP TABLE student_course_map;

CREATE TABLE student_course_map
(
  student_id integer NOT NULL,
  course_id integer NOT NULL,
  CONSTRAINT student_course_map_pkey PRIMARY KEY (student_id , course_id ),
  CONSTRAINT student_course_map_course_id_fkey FOREIGN KEY (course_id)
      REFERENCES course (id) MATCH SIMPLE
      ON UPDATE NO ACTION ON DELETE NO ACTION,
  CONSTRAINT student_course_map_student_id_fkey FOREIGN KEY (student_id)
      REFERENCES student (id) MATCH SIMPLE
      ON UPDATE NO ACTION ON DELETE NO ACTION
)
WITH (
  OIDS=FALSE
);
ALTER TABLE student_course_map
  OWNER TO postgres;

The table student_course_map will be used to story many to many relation between student and courses.


Create Hibernate Model Class Create two model calsses.One is Student and other is Courses.

package com.hibernate.tutorial;

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

public class Student {

    private Integer id;
    private String name;
    private Set courses = new HashSet();
    //constructor & getter and setter methods
 }

Create Course class;
package com.hibernate.tutorial;

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

public class Course {

    private Integer id;
    private String name;
//constructor & getter and setter methods
}

Step 3. Create Hibernate Mapping Files Create a xml file for Course and name it as 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">
<!-- Generated Jul 14, 2014 3:20:25 AM by Hibernate Tools 3.4.0.CR1 -->
<hibernate-mapping>
    <class name="com.hibernate.tutorial.Course" table="COURSE">
        <id name="id" type="java.lang.Integer">
            <column name="ID" />
            <generator class="increment" />
        </id>
        <property name="name" type="java.lang.String">
            <column name="NAME" />
        </property>
    </class>
</hibernate-mapping>

Now Create another xml file for student and name it as 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">
<!-- Generated Jul 14, 2014 3:20:25 AM by Hibernate Tools 3.4.0.CR1 -->
<hibernate-mapping>
    <class name="com.hibernate.tutorial.Student" table="STUDENT">
        <id name="id" type="java.lang.Integer">
            <column name="ID" />
            <generator class="increment" />
        </id>
        <property name="name" type="java.lang.String">
            <column name="NAME" />
        </property>
        <set name="courses" table="student_course_map" cascade="all">
            <key column="student_id" />
        <many-to-many column="course_id"  class="com.hibernate.tutorial.Course" />
        </set>
    </class>
</hibernate-mapping>

Step 4. Add following mapping line to Hibernate.hbm.xml file

<mapping resource="com/hibernate/tutorial/Student.hbm.xml"/>
 <mapping resource="com/hibernate/tutorial/Course.hbm.xml"/>

Step 5. Execute Test Cases

public class MainTest
    extends TestCase
{
    private static Session session;
    private static Student student;

    @org.junit.Test
    public Course testCourse(String name){
        Course course = new Course();
        session = HibernatePersistence.getSessionFactory().openSession();
        course.setName(name);
        session.beginTransaction();
        Integer courseId = (Integer) session.save(course);
        session.getTransaction().commit();
        course = (Course) session.get(Course.class, courseId);
        System.out.println("Course Name is : "+course.getName());
        return course;
    }

    @org.junit.Test
    public void testStudent(){
        student = new Student();
        session = HibernatePersistence.getSessionFactory().openSession();
        student.setName("ALI");
        Course mathCourse = testCourse("Math");
        Course phyCourse = testCourse("PHY");
        Set courses = new HashSet();
        courses.add(mathCourse);
        courses.add(phyCourse);
        student.setCourses(courses);
        session.beginTransaction();

        Integer studentId =(Integer) session.save(student);
        session.getTransaction().commit();
        student = (Student) session.get(Student.class, studentId);
        System.out.println("Student name is : "+student.getName());
        assertEquals("ALI",student.getName());
    }
}

Hope this article will help you in learning the basics of Hibernate. In my next article I am going to write about ‘How to make many-to-many relationship using Annotation’. I will look forward to your suggestions and questions in the comment section.


23 views0 comments

Recent Posts

See All

TRANSIENT FIELD WITH ANNOTATION VALIDATORS

Recently I got the chance to work with annotation validators @Pattern on transient field. Basically it was a password field which I had to validate first and then encrypt it and set it in another pers

Get and Load Methods in Hibernate

Both Get and Load methods in hibernate fetch row from databases. The functionality is similar but there is a difference between the way they work. hibernateSession.get() This method will return the re

Many To Many Relationship Using Annotations

This article is about how to write many to many relationships using annotations in hibernate. Many to many means that we can have many rows in one table against many rows in another table. Here is an

bottom of page