如何在hibernate中从多对多关系表中删除记录?

时间:2015-04-27 16:45:23

标签: hibernate jpa hibernate-mapping

我有三张桌子。

__lesson__ __lesson_student___ __student__
id   name   id les_id   std_id    id   name
1    Math   1  1(Math)  1(Bob)    1   Bob
2    Phys.  2  2(Phys)  1(Bob)    2   Alice
            3  1(Math)  2(Alice)

我想从Bob中移除数学。我可以这样做吗?我只想删除 lesson_student 的ID(1) 课与学生之间有很多很多关系。 我可以添加一名学生上课。但我可以从学生那里删除课程。当我从学生的收集和更新学生中删除课程时,没有任何事情发生。
Lesson.class

@ManyToMany(mappedBy = "studentLessons", fetch = FetchType.LAZY)
@Cascade(org.hibernate.annotations.CascadeType.SAVE_UPDATE)
public Set<User> getLessonStudents() {
    return lessonStudents;
}

User.class

    @ManyToMany(fetch = FetchType.LAZY)
@JoinTable(name = "lesson_student", uniqueConstraints = @UniqueConstraint(name = "uq_student_lesson", columnNames = {
        "student_id", "lesson_id" }), joinColumns = { @JoinColumn(name = "student_id", referencedColumnName = "id") }, inverseJoinColumns = { @JoinColumn(name = "lesson_id", referencedColumnName = "id") })
@Cascade(org.hibernate.annotations.CascadeType.SAVE_UPDATE)
public Set<Lesson> getStudentLessons() {
    return studentLessons;
}

我使用以下代码删除:

    @Override
public void removeLessonFromUser(Lesson les) {
    try {
        final String username = SecurityContextHolder.getContext()
                .getAuthentication().getName();
        final Criteria criteria = openSession().createCriteria(User.class);
        criteria.add(Restrictions.eq("username", username));
        User user = new User();
        user = (User) criteria.uniqueResult();

        log.info(user.getStudentLessons());
        user.getStudentLessons().remove(les);
        log.info(user.getStudentLessons());

        updateUser(user);

    } catch (final Exception e) {
        e.printStackTrace();
    }

}

我googled。我看到了orphanRemoval,它的工作只针对一对多。我需要什么?提前感谢。

1 个答案:

答案 0 :(得分:1)

您可以从lesson集中删除studentLessons对象,hibernate将负责从连接表中删除记录。

以下是示例代码:

    Session session = sessionFactory().openSession();
    session.beginTransaction();

    Student s = (Student) session.get(Student.class, 1);
    System.out.println(s.getName());

    Set<Lesson> lessons = s.getStudentLessons();

    Lesson les = (Lesson) session.get(Lesson.class, 2);
    lessons.remove(les);

    //session.update(s); -- This is not required as hibernate will do dirty checking.
    session.getTransaction().commit();
    session.close();