我看到您的实体映射存在问题,应该如下
学校- school_id(PK)
,school_name
学生- student_id(PK)
,student_name
,fk_school_id(FK)
,
老师-teacher_id(PK)
,teacher_name
,fk_school_id(FK)
*学生老师* - student_teacher_id(PK)
, fk_student_id(FK)
,fk_teacher_id(FK)
和实体类如下
学校实体
@Entity
@Table(name = "school")
public class School {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column (name = "school_id")
private int Id;
@Column(name="school_name")
private String schoolName;
@OneToMany(fetch = FetchType.LAZY, mappedBy = "school")
private Set<Student> students = new HashSet<Student>
@OneToMany(fetch = FetchType.LAZY, mappedBy = "school")
private Set<Teacher> teachers = new HashSet<Teacher>
}
学生实体
@Entity
@Table(name = "student")
public class Student {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column (name = "student_id")
private int Id;
@Column(name="student_name")
private String studentName;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "school_id", nullable = false)
private School school;
@ManyToMany(cascade = CascadeType.ALL)
@JoinTable(name = "student_teacher", joinColumns = {@JoinColumn(name = "fk_student_id") }, inverseJoinColumns = { @JoinColumn(name = "fk_teacher_id") })
private List<Teacher> teachers = new ArrayList<Teacher>();
}
教师实体
@Entity
@Table(name = "teacher")
public class Teacher {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column (name = "teacher_id")
private int Id;
@Column(name="teacher_name")
private String name;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "school_id", nullable = false)
private School school;
@ManyToMany(cascade = CascadeType.ALL)
@JoinTable(name = "student_teacher", joinColumns = {@JoinColumn(name = "fk_teacher_id") }, inverseJoinColumns = { @JoinColumn(name = "fk_student_id") })
private List<Student> students =new ArrayList<Student>();
}
希望这能解决这个问题..
由于您已在 Student_Teacher 表中将“SchoolId”声明为PK,因此不允许您为 Student_Teacher 表的 SchoolId 字段添加重复条目,但事实并非如此。因此上述关系将给出重复的 SchoolId 参考。当您要将来自同一所学校的两个不同学生添加到Student_Teacher表中时..