Hibernate - 使用注解的一对一映射

Hibernate - one to one mapping using annotations

我想将 class 地址映射到 class 员工,我目前所做的如下。

我的员工class

@Entity(name = "EMPLOYEE")
public class Employee  {
    @Id @GeneratedValue
    @Column(name="EMPLOYEEID", length =30)
    int id;
    public Employee(String string, String string2,String string3, String string4) {
    this.name=string;
    this.age=string2;
    }
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    @Column(name="NAME", length = 30)
    String name;
    @Column(name="AGE",  length = 30)
    String age;
    @OneToOne(mappedBy = "employee", cascade = CascadeType.ALL)
    Address address;
    public Address getAddress() {
        return address;
    }
    public void setAddress(Address address) {
        this.address = address;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getAge() {
        return age;
    }
    public void setAge(String age) {
        this.age = age;
    }

我的地址class是

@Entity(name="Address")
public class Address {
    @Id
    @Column(name="EMPLOYEEID", length =30)
    @GenericGenerator(name="generator", strategy="foreign", parameters = @Parameter(name="property", value="employee"))
    @GeneratedValue(generator="generator")
    int id;
    @Column(name="LINE1", length=30)
    String line1;
    @Column(name="LINE2", length=30)
    String line2;
    @Column(name="LINE3", length=30)
    String line3;
    public String getLine1() {
        return line1;
    }
    public void setLine1(String line1) {
        this.line1 = line1;
    }
    public String getLine2() {
        return line2;
    }
    public void setLine2(String line2) {
        this.line2 = line2;
    }
    public String getLine3() {
        return line3;
    }
    public void setLine3(String line3) {
        this.line3 = line3;
    }
}

但是每当我尝试执行它时,我都会收到错误

Unknown mappedBy in: com.hibernatetest.company.Employee.address, referenced property unknown: com.hibernatetest.company.Address.employee

我做错了什么?

您引用了 Address 中不存在的 属性:

@OneToOne(mappedBy = "employee", cascade = CascadeType.ALL)
Address address;

查看 OneToOne.mappedBy() 的文档:

(Optional) The field that owns the relationship. This element is only specified on the inverse (non-owning) side of the association.

因此,您的代码声明 Address 实体有一个字段 employee 拥有该关系。但是它没有这样的属性。

也许你可以用下面的代码实现这个属性(免责声明:我没有测试它,我不知道它是否适合你的特定情况):

@OneToOne(optional=false)
@JoinColumn(name="EMPLOYEEID")
Employee employee;

public Employee getEmployee() {
     return employee;
}

我认为你越来越不为人知了,因为你给了小写字母 employee ,它在任何地方都没有定义,试着把它改成

@OneToOne(mappedBy = "EMPLOYEE", cascade = CascadeType.ALL) here