我是一名开发人员,正在开发一个接收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;
}
我的控制器只有这个代码:
@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表格会有名字,Address表格会有三个属性加上customer_id。但是现在的customer_id为空。有什么想法吗?
JsonManagedReference
和JsonBackReference
注释来自动设置引用,而不是手动设置。 - coladict