我是 hibernate 的新手。我试图通过以下代码在Person和PersonDetail实体之间创建一对一映射:

@Entity
public class Person {

    private int personId;
    private String personName;
    private PersonDetail personDetail;

    @OneToOne(mappedBy="person")
    public PersonDetail getPersonDetail() {
        return personDetail;
    }

    public void setPersonDetail(PersonDetail personDetail) {
        this.personDetail = personDetail;
    }

    @Id
    @GeneratedValue
    public int getPersonId() {
        return personId;
    }

    public void setPersonId(int personId) {
        this.personId = personId;
    }

    public String getPersonName() {
        return personName;
    }

    public void setPersonName(String personName) {
        this.personName = personName;
    }
}


@Entity
public class PersonDetail {

    private int personDetailId;
    private String zipCode;
    private String job;
    private double income;

    private Person person;

    @OneToOne(cascade=CascadeType.ALL, fetch=FetchType.EAGER)
    public Person getPerson() {
        return person;
    }

    public void setPerson(Person person) {
        this.person = person;
    }

    @Id
    @GeneratedValue
    public int getPersonDetailId() {
        return personDetailId;
    }

    public void setPersonDetailId(int personDetailId) {
        this.personDetailId = personDetailId;
    }

    public String getZipCode() {
        return zipCode;
    }

    public void setZipCode(String zipCode) {
        this.zipCode = zipCode;
    }

    public String getJob() {
        return job;
    }

    public void setJob(String job) {
        this.job = job;
    }

    public double getIncome() {
        return income;
    }

    public void setIncome(double income) {
        this.income = income;
    }

}

我希望PersonDetail应该是拥有的实体(反之亦然,但我只想测试)。我不理解的是我在Person实体中使用的mappingBy属性的用法。如果删除它,则会出现以下错误:
“无法确定com.hibernate.onetoonemapping.PersonDetail的类型,在表:Person上,对于列:[org.hibernate.mapping.Column(personDetail)]”

此mappingBy属性有什么作用?我已经读过,mappedBy属性放在非所有者的那一侧。但是它到底是做什么的呢?

最佳答案

这意味着实体之间的关系已经被映射,因此您不必重复两次。您只需使用mapledBy属性说“嘿,就在那完成了”。

关于hibernate - 注释中的mapledBy属性的含义?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/8962878/

10-12 17:16