gpt4 book ai didi

java - Hibernate - 使用注释的一对一映射

转载 作者:太空宇宙 更新时间:2023-11-04 06:18:22 24 4
gpt4 key购买 nike

我想将类(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;
}

我的地址类别是

@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;
}

关于java - Hibernate - 使用注释的一对一映射,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27773326/

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