How to update a @ManyToOne relationship with Spring Data REST?

a 夏天 提交于 2019-12-04 11:35:13

问题


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?


回答1:


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



来源:https://stackoverflow.com/questions/34754992/how-to-update-a-manytoone-relationship-with-spring-data-rest

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!