How to update a @ManyToOne relationship with Spring Data REST?
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"
}
}
The relationship in the User entity is:
@ManyToOne(optional = false)
@JoinColumn(name = "account_state")
@Getter @Setter private AccountState accountState;
Now I try to change the account status using a PATCH request on /users/123 and the payload:
{"accountState":{"id":0}}
But I get an error:
"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"
I also tried to use @HandleBeforeSave/@HandleBeforeLinkSave to fetch the new AccountState from the repository and replace user.accountStatus with no success.
What am I doing wrong?
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"
}
So you are using the URI of your account state to reference the resource to assign
链接地址: http://www.djcxy.com/p/89602.html