Many-to-Many Example Hibernate

Many-to-Many Example Hibernate

Many-to-Many Hibernate

There are two styles to maintain association in many-to-many Hibernate – a) using Set and b) using Map.

  1. Many-To-many Relationship: In many-to-many relationship, as the name implies, many records of one table are associated with many records of another table.
  2. Concept: One Student may attend multiple courses and similarly one course may be attended by multiple students. You can say, it is many-to-many as multiple students vs multiple courses. Infact, it is one-to-many relationship. Each record (of a group of multiple records) of one table is associated with multiple records of another table.
  3. Association in tables: studentId and courseId are the primary keys in studentinfo and courseinfo tables. studentId is the foreign key, in courseinfo, associated with courseId. Similarly, courseId is the foreign key, in studentinfo, associated with studentId. This mapping is done with <key> element in mapping table. <key> represents always a foreign key in a database table.
  4. Bean coding: Two beans exist, Student and Course. A Set is created in Student class to which all the courses attended by the student are added. Similarly, another Set is created in Course class to which all the students attending the course are added. Here, Set is preferred to List for the reason one student does not go to the same course twice and similarly one course does not have the same student twice. Instead of Set, List also can be used where applicable in other cases. But one thing must be clear, in many-to-many association, it is a must to use a collection class on both the sides.

Following are the variables declared in Student and Course classes.

Student Course
private short studentId; private short courseId;
private String studentName; private String courseName;
private short marks; private String duration;
private Set courses; private Set students;

Note: As we are not creating tables in advance and we are allowing the Hibernate (hbm2ddl) to create the tables for us, studentId is declared as short (instead of int) as it is converted into number(5) occupying less space. Learn how to use short instead of integer in client program.

Notice that Set exists in both classes. Many-to-many is always bidirectional.

We expect two tables representing two bean classes. You are right. But in many-to-many, we require one extra table that maintains (joins) the data of foreign keys of the two tables. We name this mediator join table as keysinfo.

So, total we have two beans, three tables, two XML files. Let us explore them one by one.

1. Bean Program: Student.java

2. Bean Program: Course.java

3. Configuration XML file: hibernate.cfg.xml

4. Mapping XML file: Student.hbm.xml

Observe the special join table name, and cascade.

We have chosen Set to store the courses attended by the student. The join table is keysinfo. <key> means that student_id column of studentinfo should be treated as foreign key. Many-to-Many association of student is with Course. student_id and course_id are to be mapped in keysinfo table.

5. 1st Client Program: InsertClient.java (to insert records in tables)

std1.setStudentId((short)100);

The parameter 100 is converted into short as studentId is declared as short in the Student bean program. The whole number, in Java by default, is treated as int and a floating-point number as double.

Number of courses, course1 and course2 are added to the Set object set1. With setCourses() method, the Set set1 is added to Student object. The set1 object takes care of inserting Course object into courseinfo table.

Database table data types created by the Hibernate.

Many-to-Many Example Hibernate

Records entered by Hibernate after executing the client program – InsertClient.java

Many-to-Many Example Hibernate

Console screenshot to know what SQL statements are executed by Hibernate.

Many-to-Many Example Hibernate

6. 2nd Client Program: RetrieveClient.java (to retrieve records from tables)

// Student std = (Student) s.get(Student.class,new Integer(100)); // general style
Student std = (Student) s.get(Student.class, new Short((short)100));

The general style does not work here as the studentId is declared s short in Student table. Infact, the second parameter of get() method is an object of Serializable. As Short wrapper class is serialized (infact, its super class Number is serialized), it can also be included as parameter.

Many-to-Many Hibernate

7. 3rd Client Program: DeleteClient.java (to retrieve records from tables)

You have seen how to insert and retrieve records in many-to-many association. Now let us write one more program to delete the records. When a student object is deleted, its associated courses also deleted.

Console screenshot to know what SQL statements are called to delete one Student record. Records from keysinfo (join table) are also deleted.

Many-to-Many Example Hibernate

4 thoughts on “Many-to-Many Example Hibernate

  1. vithu

    Hello sir,
    here if we delete one record with ‘100’, all the records are deleted including ‘101’ record also and the table is empty .
    could you please tell me the reason or why it happens?

      1. vithu

        Which means we cant use s.delete(). so then how can we delete only 100’s record. How to use delete Query here?
        could you please explain little bit?

Leave a Reply

Your email address will not be published. Required fields are marked *