top of page
index-1-1.jpg
Writer's pictureAurora Solutions

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 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.

Step 2. Create Hibernate Model Class Create Student Class as below

@Entity
@Table(name = "student")
public class Student {

    private Integer id;
    private String name;
    private Set courses = new HashSet();

    @Id
    @GenericGenerator(name="generator", strategy="increment")
    @GeneratedValue(generator="generator")
    @Column(name = "id", unique = true, nullable = false)
    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }
    @Column(name = "name", unique = true, nullable = false)
    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    @ManyToMany(fetch = FetchType.LAZY, mappedBy = "students")
    public Set getCourses() {
        return courses;
    }
    public void setCourses(Set courses) {
        this.courses = courses;
    }

    @Override
    public String toString() {
        return "Student [id=" + id + ", name=" + name + ", courses=" + courses
                + "]";
    }

}

Create Course class

@Entity
@Table(name = "course")
public class Course {

    private Integer id;
    private String name;
    private Set students = new HashSet(0);

    @Id
    @GenericGenerator(name="generator", strategy="increment")
    @GeneratedValue(generator="generator")
    @Column(name = "id", unique = true, nullable = false)
    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    @Column(name = "name", unique = true, nullable = false)
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }

    @ManyToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL)
    @JoinTable(name = "student_course_map", joinColumns = {
            @JoinColumn(name = "course_id", nullable = false, updatable = false) },
            inverseJoinColumns = { @JoinColumn(name = "student_id",
                    nullable = false, updatable = false) })
    public Set getStudents() {
        return students;
    }

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

    @Override
    public String toString() {
        return "Course{" +
                "id=" + id +
                ", name='" + name + ''' +
                ", students=" + students +
                '}';
    }
}

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

<mapping class="com.hibernate.tutorial.Course"/>
<mapping class="com.hibernate.tutorial.Student"/>

Step 4. 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(){
        Set students = new HashSet();
        student = new Student();
        session = HibernatePersistence.getSessionFactory().openSession();
        student.setName("ALI");
        students.add(student);
        Course mathCourse = testCourse("Math");
        mathCourse.setStudents(students);
        Course phyCourse = testCourse("PHY");
        phyCourse.setStudents(students);
        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 and in best of your ways. I will look forward to your suggestions and questions in the comment section. I will be very happy on your suggestion and if you have any question.


28 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...

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...

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...

Commentaires


bottom of page