【发布时间】:2014-01-30 06:25:15
【问题描述】:
我正在尝试通过 RESTFUl 服务以具有嵌套关系的形式保存 2 个对象。即,一个办公室有 2 名员工。
但是,从下面的示例可以看出,如果不先保存 office,我将无法知道 officecode 为 20。没有:
"officecode":"20"
虽然json对象是嵌套的,但是,我保存员工和办公室OK,但是他们没有相互关联。
那么如何在 1 次提交中保存嵌套对象?
实体看起来像:
// Property accessors
@Id
@Column(name = "OFFICECODE", unique = true, nullable = false, length = 10)
public String getOfficecode() {
return this.officecode;
}
....
@OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY, mappedBy = "office")
public Set<Employee> getEmployees() {
return this.employees;
}
这是拯救办公室的其余电话:
@RequestMapping(value = "/Office", method = RequestMethod.POST)
@ResponseBody
public Office newOffice(@RequestBody Office office) {
officeService.saveOffice(office);
return officeDAO.findOfficeByPrimaryKey(office.getOfficecode());
}
这是我发布的 JSON 对象:
{
"state":"CA",
"country":"USA",
"officecode":"20",
"city":"Vancouver",
"phone":"+1 650 219 4782",
"addressline1":"100 Market Street",
"addressline2":"Suite 300",
"postalcode":"94080",
"territory":"NA",
"employees":[
{
"extension":"x5800",
"employeenumber":2001,
"lastname":"joe",
"firstname":"joe",
"email":"joe@classicmodelcars.com",
"reportsto":null,
"jobtitle":"President",
"pay":null,
"officecode":"20"
},
{
"extension":"x5800",
"employeenumber":2002,
"lastname":"mary",
"firstname":"mary",
"email":"mary@classicmodelcars.com",
"reportsto":null,
"jobtitle":"Vice President",
"pay":null
"officecode":"20"
}
]
}
【问题讨论】:
-
我更新了答案,请参阅下文如何将外键从员工表填充到办公室表。
-
你试过了吗?
标签: json spring model-view-controller nested