【发布时间】:2017-08-31 22:58:49
【问题描述】:
我正在开发一个将接收 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 是 null。
有什么想法吗?
【问题讨论】:
-
是的,需要设置address.customer字段,不能留空。
-
如果您使用 Jackson 进行 JSON 转换,您可以使用
JsonManagedReference和JsonBackReference注释自动设置引用,而不是手动设置。
标签: java json postgresql hibernate jpa