[英]JPA - field must have same number of columns as the referenced primary key
在我的项目中,我有两个班级: School
和Teacher
。 一所学校可以指派多名教师。 到目前为止,这是我的代码:
@Entity
@Table(name = "schools", uniqueConstraints = {
@UniqueConstraint(columnNames = {
"name"
}})
public class School {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
...
@OneToMany(fetch = FetchType.LAZY)
@JoinTable(name = "teachers",
joinColumns = @JoinColumn(name = "school_id"),
inverseJoinColumns = @JoinColumn(name = "teacher_id"))
private Set<Teacher> teachersList = new HashSet<>();
另一个类如下所示:
@Entity
@Table(name = "teachers", uniqueConstraints = {
@UniqueConstraint(columnNames = {
"id"
})
})
public class Teacher {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
...
现在,当我尝试构建此项目时,出现错误:
org.hibernate.MappingException: Foreign key (FK4hetjkgnpo354f7uwax5aewc0:teachers
[teacher_id])) must have same number of columns as the
referenced primary key (teachers [school_id,teacher_id])
我迷路了。 我到底错过了什么? 谢谢!
@JoinTable 用于 ManyToMany 关系,您必须在Many Entity 端(Teachers)中使用 @JoinColumn
尝试这个:
public class Teacher{
//...
@ManyToOne
@JoinColumn(name="fk_school_id") // this is your foreign key in your Teacher table of your DB
private School school;
}
但是,如果您还想检索每所学校的教师列表,则必须将其放入您的单一实体(学校)中:
@OneToMany(mappedBy="school")
private List<Teacher> teachers = new ArrayList();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.