manytomany注解:
@ManyToMany
注释:表示此类是多对多关系的一边,mappedBy 属性定义了此类为双向关系的维护端,注意:mappedBy 属性的值为此关系的另一端的属性名。
例如,在Student类中有如下方法:
被控方:
@ManyToMany(fetch = FetchType.LAZY, mappedBy = “students”)
public Set getTeachers() {
return teachers;
}
那么这里的“students”就是Teachers的一个属性,通常应该是这样的:
Set students;
另一端的getStudents方法如下所示:
@ManyToMany(cascade = CascadeType.PERSIST, fetch = FetchType.LAZY)
@JoinTable(name = "Teacher_Student",
joinColumns = {@JoinColumn(name = "Teacher_ID", referencedColumnName = "teacherid")},
inverseJoinColumns = {@JoinColumn(name = "Student_ID", referencedColumnName ="studentid")})
public Set<Student> getStudents() {
return students;
}
删除数据时级联删除中间表的数据
删除主控方数据时,要先把中间表的主控方属性值set为null,才能删除成功,否则会报错