gpt4 book ai didi

java - JPA - 字段的列数必须与引用的主键相同

转载 作者:行者123 更新时间:2023-12-01 19:05:18 25 4
gpt4 key购买 nike

在我的项目中,我有两个类:SchoolTeacher。一所学校可以指派多名教师。这是我到目前为止的代码:

@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 实体端(教师)使用@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();

关于java - JPA - 字段的列数必须与引用的主键相同,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59571554/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com