多对多关系,更新引用的Set(更新连接表)抛出NonUniqueObjectException

时间:2013-12-16 19:49:36

标签: sql hibernate java-ee

我正在使用hibernate。我在StudentGroup类之间存在多对多关系。有一个名为student_group加入表,其中包含student_idgroup_id列。

Student 类:

    @Entity
    @Table(name = "student")
    public class Student {
      private int student_id; //primary key

      @ManyToMany(mappedBy = "students")
      private Set<Group> groups = new HashSet<Group>();

      @ManyToMany(cascade = {CascadeType.ALL})
      @JoinTable(name="student_group",
                joinColumns={@JoinColumn(name="student_id")},
                inverseJoinColumns={@JoinColumn(name="group_id")})
      public Set<Group> getGroups() {
        return groups;
      }

      public void setGroups(Set<Group> groups) {
        this.groups = groups;
      }

      //Setter & Getter for student_id
      ...
    }

Group 类:

@Entity
@Table(name = "group")
public class Group {
  private int group_id;//primary key
  private Set<Student> students = new HashSet<Student>();

  @ManyToMany(cascade = {CascadeType.ALL})
  @JoinTable(name="student_group",
            joinColumns={@JoinColumn(name="group_id")},
            inverseJoinColumns={@JoinColumn(name="student_id")})
  public Set<Student> getStudents() {
    return students;
  }

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

  //Getter & Setting for group_id
  ...

}

在我的主程序中,我有一个功能,第一次从数据库中找到 student ,然后添加 {{ 1}} group最后尝试将更新的 student 保存到数据库:

student

(上面函数中的public void addGroupToStudent(int studentId, Group newGroup){ //open a session & query the database to get a student by id Session session = sessionFactory.openSession(); Student student = loadStudentById(session, id); //Get above student's groups Set<Group> groups = student.getGroups(); //Add the new group groups.add(newGroup); //SaveAndUpdate the student in database Transaction transaction = session.beginTransaction(); try { session.saveOrUpdate(student); transaction.commit(); } catch (final HibernateException e) {...} } 参数是使用另一个会话和查询从数据库中检索的。)

但是上面的函数引发了以下异常:

newGroup

我哪里错了?如何摆脱这种异常?一般来说,我只想更新数据库中的学生组,然后轮流应该更新连接表。

0 个答案:

没有答案