Search code examples
hibernatemany-to-manyduplicatesrecord

Hibernate Many-to-Many, duplicates same record


I tried Hibernate Mapping Many-to-Many using Annotations with the example given in vaannila.

http://www.vaannila.com/hibernate/hibernate-example/hibernate-mapping-many-to-many-using-annotations-1.html

        Set<Course> courses = new HashSet<Course>();
        courses.add(new Course("Maths"));
        courses.add(new Course("Computer Science"));

        Student student1 = new Student("Eswar", courses);
        Student student2 = new Student("Joe", courses);
        session.save(student1);
        session.save(student2);

This thing works fine. But if I try to add another Course later, to a existing student like,

        Set<Course> courses = new HashSet<Course>();
        courses.add(new Course("Science"));
        Student student = new Student("Eswar", courses);
        session.save(student);

It duplicates the student Eswar again in the table.

        +------------+--------------+
        | STUDENT_ID | STUDENT_NAME |
        +------------+--------------+
        |          1 | Eswar        |
        |          2 | Joe          |
        |          3 | Eswar        |
        +------------+--------------+

Can't I add the courses to the existing Eswar? I really appreciate your help for this problem.


Solution

  • You first need to get Student from database and then add courses to that object, and then save the fetched object.

    This way, You are creating a new Student object, this new student object have a null in the "ID" instance variable. It seems to me that Hibernate must be mapping this instance variable to the primary key for look up, if id is found, record is updated else new record is inserted..

    and yes, if u need to add the course for existing student, U might want to first get set from fetched student object, then add a course in that set, then save......else the new hash set will only contain the new course, and previous record will be overwritten.