【问题标题】:JPA - field must have same number of columns as the referenced primary keyJPA - 字段的列数必须与引用的主键相同
【发布时间】:2020-04-21 14:28:53
【问题描述】:

在我的项目中,我有两个类: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])

我迷路了。我到底错过了什么?谢谢!

【问题讨论】:

  • teachers 表是否有 school_id 列?如果是这样:Teacher-class 是否有对应的School-字段映射为@ManyToOne
  • 嗯,教师没有 schoold_id。此外,Teacher 类还没有任何对应的 School-field。我怎样才能申报所有这些缺失的数据?非常感谢您的帮助!

标签: java jpa foreign-keys mapping


【解决方案1】:

@JoinTable 用于多对多关系,您必须在 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();

【讨论】:

    猜你喜欢
    • 2021-12-20
    • 1970-01-01
    • 1970-01-01
    • 2015-09-18
    • 1970-01-01
    • 2019-11-18
    • 1970-01-01
    • 2014-07-27
    • 2019-07-30
    相关资源
    最近更新 更多