2014-01-11 45 views
1

我想通過RESTFUl服務在嵌套關係的窗體中保存2個對象。也就是說,一個辦公室有2名員工。如何在春天保存嵌套的json對象mvc

然而,正如你可以從下面的示例中看到的,沒有保存的辦公室,我就無法知道officecode爲20.在不:

「officecode」:「20」

雖然json對象是嵌套的,但是,我保存了員工和辦公室,但他們沒有關聯。

如何保存嵌套對象在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; 
    } 

這裏是REST調用保存辦公室:

@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":"[email protected]", 
"reportsto":null, 
"jobtitle":"President", 
"pay":null, 
"officecode":"20" 
}, 
{ 
"extension":"x5800", 
"employeenumber":2002, 
"lastname":"mary", 
"firstname":"mary", 
"email":"[email protected]", 
"reportsto":null, 
"jobtitle":"Vice President", 
"pay":null 
"officecode":"20" 
} 
] 

} 
+0

我更新了答案,請參閱以下如何填充從員工表到外部表的外鍵。 –

+0

你有沒有去過它? –

回答

2

OK你正在使用Cascade,但它仍然不起作用。這是因爲員工被添加到辦公室的方式。

的JSON解組是這樣的員工關聯:

office.getEmployees().add(employee) 

這是不夠的員工連接到辦公室,因爲office.getEmployees是關係的非持有端,即休眠不跟蹤。

結果是辦公室和員工全部插入,但員工到辦公室的外鍵爲空。

爲了解決這個問題,節省您需要全體員工鏈接到辦公室之前,通過將這種方法辦公室和調用它的權利之前堅持:

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

這樣的關係的擁有方( Employee.office)正在被設置,所以Hibernate將被通知新的關聯並且通過填充從員工到辦公室的外鍵字段來堅持它。

,如果你想了解更多關於Hibernate雙向關係的擁有方的ocasional需要我在這裏的答案this thread見。

+0

奇怪,我@OneToMany是在不同的地方,我已經更新的問題,以反映這一點。謝謝。 –

+0

更新我在這個線程的答案有關的擁有方,爲什麼減少了員工與空外鍵的這種行爲是正常的,怎樣做是http://stackoverflow.com/questions/2749689/what-is-the-擁有側功能於一個-ORM映射/ 21068644#21068644 –