【问题标题】:how to save nested json object in a spring mvc如何在spring mvc中保存嵌套的json对象
【发布时间】: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


【解决方案1】:

好的,您正在使用 Cascade,但它仍然无法正常工作。这是因为员工被添加到办公室的方式。

JSON unmarshaller 像这样关联员工:

office.getEmployees().add(employee)

这不足以将员工链接到办公室,因为 office.getEmployees 是关系的非拥有方,Hibernate 不会跟踪。

结果是office和employees都插入了,但是从employee到office的外键为空。

要解决这个问题,在保存之前,您需要将所有员工链接到办公室,方法是将此方法添加到 Office 并在持久化之前调用它:

public void linkEmployees() {
    for (Employee employee : employees) {
        employee.setOffice(this);
    }
}

这样设置关系的拥有方 (Employee.office),因此 Hibernate 将收到新关联的通知,并通过从员工到办公室填充外键字段来保持它。

如果您想了解更多关于 Hibernate 双向关系和偶尔需要拥有方的信息,请参阅我在 this thread 中的回答。

【讨论】:

  • 奇怪,我的@OneToMany 在不同的地方,我已经更新了问题以反映这一点。谢谢。
  • 我在这个线程上更新了关于拥有方的答案以及为什么用空外键保存员工的这种行为是正常的以及如何处理它stackoverflow.com/questions/2749689/…
猜你喜欢
  • 2012-10-05
  • 1970-01-01
  • 2013-09-21
  • 2016-03-01
  • 2014-05-08
  • 1970-01-01
  • 1970-01-01
  • 2018-03-10
  • 2017-02-25
相关资源
最近更新 更多