我有一个班级Subject
,
@Entity
@IdClass(SubjectId.class)
@Data
public class Subject {
@Id
private String name;
@ManyToOne
@JsonBackReference
@Id
private Teacher teacher;
@OneToMany(mappedBy = "student")
private List<StudentSubject> students;
}
其复合ID在SubjectId
类中定义,
public class SubjectId implements Serializable{
private String name;
private Teacher teacher;
public SubjectId(String name, Teacher teacher) {
this.name = name;
this.teacher = teacher;
}
SubjectId(){}
}
编译时,我收到错误
org.hibernate.MappingException:集合外键映射列数错误:com.example.Subject.students类型:component [name,teacher]
虽然这会将错误指向学生元素,但是在我删除了Subject的自动生成的ID之后发生了错误,并将其替换为名称和教师的组合。
无论如何,students
元素在StudentSubject
类中映射,
@Entity
@IdClass(StudentSubjectId.class)
public @Data
class StudentSubject {
String studentId;
@ManyToOne
@Id
private Subject subject;
@ManyToOne
@Id
private Student student;
答案 0 :(得分:1)
发生此错误时,通常意味着hibernate在正确数量的列上映射外键时出现问题。
在上面的情况中,subject
类中的StudentSubject
实体未被映射到两列,即name
和teacher_email
(这是Teacher
表)。
要解决此类错误,请添加@JoinColumns
,如下所示
class StudentSubject {
@Id
@ManyToOne
@JoinColumns({
@JoinColumn(referencedColumnName = "name"),
@JoinColumn(referencedColumnName = "teacher_email") })
private Subject subject;
}
referencedColumnName
指的是外表中列的名称。
答案 1 :(得分:0)
尝试以这种方式设置OneToMany:
@OneToMany(
cascade = CascadeType.ALL,
orphanRemoval = true)
private List<StudentSubject> students = new ArrayList<>();