如何使用Spring Data REST更新@ManyToOne关系? [英] How to update a @ManyToOne relationship with Spring Data REST?
问题描述
我将Spring Data REST与JPA结合使用.我有一个User实体,该实体与另一个在单独的RDBMS表中建模的称为AccountStatus的多对一关系. JSON表示形式如下:
I use Spring Data REST with JPA. I have a User entity that has a many to one relationship with another called AccountStatus modeled in a separate RDBMS table. The JSON representation looks like this:
{
"id": "123"
"username": "user1",
"accountStatus": {
"id": "1",
"status": "Active"
}
}
用户实体中的关系为:
@ManyToOne(optional = false)
@JoinColumn(name = "account_state")
@Getter @Setter private AccountState accountState;
现在,我尝试使用/users/123和有效负载上的PATCH请求来更改帐户状态:
Now I try to change the account status using a PATCH request on /users/123 and the payload:
{"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.
I also tried to use @HandleBeforeSave/@HandleBeforeLinkSave to fetch the new AccountState from the repository and replace user.accountStatus with no success.
我在做什么错了?
推荐答案
这实际上取决于您是否为AccountState
导出了存储库.如果您这样做,可以使用PATCH
相对于/users/{id}
来更新帐户状态:
It really depends if you have an exported repository for AccountState
. If you do you can update your account state with a PATCH
against /users/{id}
:
{
"accountState": "http://localhost:8080/accountStates/2"
}
因此,您正在使用帐户状态的URI来引用要分配的资源
So you are using the URI of your account state to reference the resource to assign
这篇关于如何使用Spring Data REST更新@ManyToOne关系?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!