小编典典

@OneToOne与@JoinColumn的双向映射

hibernate

假设我有个人

class Person{
    @Id Integer id;

    @OneToOne
    @JoinColumn(name = "person_id")
    Job myJob;
}

和工作

class Job{
    @Id Integer id;
    Integer person_id;

    @OneToOne
    @PrimaryKeyJoinColumn(name = "person_id")
    Person currentWorker;
}

提取时,我无法将Person和Job映射到其他实体。
我在做什么错?


阅读 655

收藏
2020-06-20

共1个答案

小编典典

您的代码应为:

@Entity
public class Person implements Serializable {

    @Id Integer id;

    @OneToOne
    @JoinColumn(name = "id")
    Job myJob;
}

@Entity
public class Job implements Serializable {

    @Id Integer id;

    @OneToOne(mappedBy = "myJob")
    Person currentWorker;
}

(尝试从工作中删除重复的列’person_id’)

或其他共享主键的方法:

@Entity
public class Person {
    @Id Integer id;

    @OneToOne(cascade = CascadeType.ALL)
    @PrimaryKeyJoinColumn
    Job myJob;
}

@Entity
public class Job {
    @Id Integer id;
}
2020-06-20