2016-01-12 33 views
6

我使用Spring Data REST和JPA。我有一個用戶實體與另一個叫做AccountStatus的多對一關係建模在一個單獨的RDBMS表中。 JSON表示如下:如何更新與Spring Data REST的@ManyToOne關係?

{ 
    "id": "123" 
    "username": "user1", 
    "accountStatus": { 
    "id": "1", 
    "status": "Active" 
    } 
} 

在用戶實體的關係是:

@ManyToOne(optional = false) 
@JoinColumn(name = "account_state") 
@Getter @Setter private AccountState accountState; 

現在我嘗試使用上/用戶/ 123和有效載荷補丁請求更改賬戶狀態:

{"accountState":{"id":0}} 

但我得到一個錯誤:

"identifier of an instance of com.domain.account.AccountState was 
    altered from 1 to 0; nested exception is org.hibernate.HibernateException: 
    identifier of an instance of com.domain.account.AccountState was 
altered from 1 to 0" 

我也嘗試使用@ HandleBeforeSave/@ HandleBeforeLinkSave從存儲庫中提取新的AccountState,並取代user.accountStatus而沒有成功。

我在做什麼錯?

+0

的[休眠可能重複:如何解決「實例標識符從X更改爲Y」?](http://stackoverflow.com/questions/4179166/hibernate-how-to-fix-identifier-of-an-instance-altered-from-x-to- y) – Makoto

+0

@Makoto,我想另外一個問題是關於改變一個擁有實體的PK,我的問題是改變一個沒有在用戶和AccountState之間定義級聯的子關係。 – florind

回答

8

這真的取決於您是否有導出的存儲庫AccountState。如果你這樣做,你可以更新您的帳戶狀態的PATCH/users/{id}

{ 
    "accountState": "http://localhost:8080/accountStates/2" 
} 

所以你使用自己的帳戶狀態的URI引用資源分配

+0

Hey Mathias,我遇到同樣的問題,但由於各種原因,我們實例中的「accountState」未導出。有沒有辦法做到這一點,而不是出口? – pasquers

+0

@pasquers我不這麼認爲 - 我想你將不得不爲更新創建一個自定義控制器,並將其鏈接添加到你擁有的資源中 –

+0

有人可以解釋爲什麼它不適用於PUT? – Toilal

相關問題