gpt4 book ai didi

java - 如何将一对一 hibernate 实体映射到一对多数据库结构?

转载 作者:行者123 更新时间:2023-12-04 23:53:11 26 4
gpt4 key购买 nike

我正在尝试做一个一对一的双向 hibernate 实体。当我保存父对象时,它没有填写子对象上的 customer_id。我不知道为什么。我希望有某种方法可以通过 hibernate 注释告诉它执行此操作。

我的实体看起来像

@Table(name = "customer")
public class CustomerEntity {

@Id
@Column(name = "id")
private Long id;

@OneToOne(mappedBy = "customer", fetch = FetchType.LAZY, cascade = CascadeType.ALL)
private CustomerAddressEntity customerAddress;

..more
}

@Table(name="customer_address")
@GenericGenerator(name="generator", strategy="increment")
public class CustomerAddressEntity {

@Id
@Column(name = "id")
@GenericGenerator(name = "sequence_customer_address_id", strategy = "com.abc.enrollment.service.IdGenerator")
@GeneratedValue(generator = "sequence_customer_address_id")
private Long id;

@OneToOne
@JoinColumn(name = "customer_id", referencedColumnName = "id")
private CustomerEntity customer;

..more
}

表格看起来像

CREATE TABLE enroll.customer_address(
id NUMBER(38,0) NOT NULL,
customer_id NUMBER(38,0) )

CREATE TABLE enroll.customer (
id NUMBER(38,0) NOT NULL)

hibernate 版本 = "5.0.0.CR2"


除了已接受的答案外,我还必须做一些其他事情才能让它发挥作用。我会把它贴在这里以防它帮助别人。我们使用 lombok 并对对象进行 JSON 序列化。以下注释避免了堆栈溢出错误。

@ToString(exclude = "customer")
@EqualsAndHashCode(exclude = "customer")
public class CustomerAddressEntity {

@JsonIgnore
private CustomerEntity customer;

最佳答案

既然是双向关系,就应该在两端都设置。意思是,在parent中设置对子对象的引用,在child中设置对父对象的引用。它应该工作。像这样

Customer cust = new Customer();
CustomerAddress custAddr = new CustomerAddress();
cust.setCustomerAddress( custAddr );
custAddr.setCustomer( cust );

关于java - 如何将一对一 hibernate 实体映射到一对多数据库结构?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31974176/

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