gpt4 book ai didi

java - JPA ManyToOne/OneToMany 没有在 child 身上插入值(value)

转载 作者:行者123 更新时间:2023-11-29 12:55:58 26 4
gpt4 key购买 nike

我正在开发一个将接收 JSON 的 Rest API。我需要将 JSON 正确保存在 Postgres 数据库中。

现在我有:

@Entity
public class Customer {
@Id
@GeneratedValue(strategy = AUTO)
private Long id;
private String name;
@OneToMany(mappedBy = "customer", cascade = ALL)
private List<Address> address;
}

@Entity
public class Address {
@Id
@GeneratedValue(strategy = AUTO)
private Long id;
private String city;
private String number;
private String country;
@ManyToOne
@JoinColumn(name = "customer_id", nullable = false)
private Customer customer;
}

我的 Controller 只有这个:

@RequestMapping(method = POST)
public ResponseEntity create(@RequestBody Customer customer) {
Customer customerSaved = repository.save(customer);
return new ResponseEntity(customerSaved, CREATED);
}

当我发送如下 JSON 时:

{
"name":"A name",
"address":[
{
"country":"Brazil",
"city":"Porto Alegre",
"number":"000"
}
]
}

我原以为 Customer 表会有 name,而 Address 表有这三个属性加上 customer_id。但是现在的 customer_id 是空的。

有什么想法吗?

最佳答案

修改List地址的setter方法如下:

public void setAddress(Set<Address> address) {

for (Address child : address) {
// initializing the TestObj instance in Children class (Owner side)
// so that it is not a null and PK can be created
child.setCustomer(this);
}
this.address = address;
}

Hibernate - One to many relation - foreign key always "null"

关于java - JPA ManyToOne/OneToMany 没有在 child 身上插入值(value),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43246259/

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