我在类似的情况下找到了正确的映射(并在广泛的情况下使用JUnit进行了测试)。我认为我不会发布测试代码,因为适应该示例将花费很长时间。无论如何,关键是:
mappedBy
注释不使用属性,使用连接列- 列出可能的
CascadeTypes
排除REMOVE
以OP为例
@ManyToMany(fetch = FetchType.LAZY, cascade = { CascadeType.DETACH, CascadeType.MERGE, CascadeType.REFRESH, CascadeType.PERSIST }, targetEntity = Course.class)@JoinTable(name = "XTB_STUDENTS_COURSES", inverseJoinColumns = @JoinColumn(name = "COURSE_ID", nullable = false, updatable = false), joinColumns = @JoinColumn(name = "STUDENT_ID", nullable = false, updatable = false), foreignKey = @ForeignKey(ConstraintMode.CONSTRAINT), inverseForeignKey = @ForeignKey(ConstraintMode.CONSTRAINT))private final Set<Course> courses = new HashSet<>();@ManyToMany(fetch = FetchType.LAZY, cascade = { CascadeType.DETACH, CascadeType.MERGE, CascadeType.REFRESH, CascadeType.PERSIST }, targetEntity = Student.class)@JoinTable(name = "XTB_STUDENTS_COURSES", joinColumns = @JoinColumn(name = "COURSE_ID", nullable = false, updatable = false), inverseJoinColumns = @JoinColumn(name = "STUDENT_ID", nullable = false, updatable = false), foreignKey = @ForeignKey(ConstraintMode.CONSTRAINT), inverseForeignKey = @ForeignKey(ConstraintMode.CONSTRAINT))private final Set<Student> students = new HashSet<>();
广泛的JUnit测试证明:
- 我可以为学生添加课程,反之亦然
- 如果我从学生中删除课程,则该课程不会被删除
- 反之亦然
- 如果我删除一个学生,则所有课程均被分离,但仍保留在数据库中(对其他学生而言)
- 反之亦然
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)