休眠多对多,重复相同的记录 [英] Hibernate Many-to-Many, duplicates same record

查看:163
本文介绍了休眠多对多,重复相同的记录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

我尝试使用注释中的多对多使用Hibernate映射/hibernate/hibernate-example/hibernate-mapping-many-to-many-using-annotations-1.htmlrel =nofollow> http://www.vaannila.com/hibernate/hibernate-example/hibernate-mapping -many-to-many-using-annotations-1.html

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

它在表中再次重复了学生Eswar。

It duplicates the student Eswar again in the table.

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

我无法将课程添加到现有的Eswar中?
我非常感谢您对这个问题的帮助。

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

推荐答案

您首先需要从数据库中获取学生,然后添加课程对于该对象,然后保存获取的对象。

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

这样,您正在创建一个新的Student对象,此新学生对象在ID实例中具有空值变量。在我看来,Hibernate必须将此实例变量映射到主键进行查找,如果找到id,则记录更新,否则插入新记录。

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

是的,如果你需要为现有的学生添加课程,U可能想先从获取的学生对象中获取设置,然后在该组中添加一个课程,然后保存......否则新的哈希集只包含新课程和以前的记录将被覆盖。

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.

这篇关于休眠多对多,重复相同的记录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆