如何使用Spring Data REST更新@ManyToOne关系?

flo*_*ind 7 spring jpa spring-data spring-data-rest

我在JPA中使用Spring Data REST.我有一个User实体,它与另一个名为AccountStatus的多对一关系在一个单独的RDBMS表中建模.JSON表示如下所示:

{
   "id": "123"
   "username": "user1",
   "accountStatus": {
     "id": "1",
     "status": "Active"
   }
}
Run Code Online (Sandbox Code Playgroud)

用户实体中的关系是:

@ManyToOne(optional = false)
@JoinColumn(name = "account_state")
@Getter @Setter private AccountState accountState;
Run Code Online (Sandbox Code Playgroud)

现在我尝试使用/ users/123上的PATCH请求和有效负载更改帐户状态:

{"accountState":{"id":0}}
Run Code Online (Sandbox Code Playgroud)

但是我收到一个错误:

 "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"
Run Code Online (Sandbox Code Playgroud)

我还尝试使用@HandleBeforeSave/@ HandleBeforeLinkSave从存储库中获取新的AccountState并替换user.accountStatus但没有成功.

我究竟做错了什么?

Mat*_*nkt 10

这实际上取决于您是否有导出的存储库AccountState.如果你这样做,你可以更新与您的帐户状态PATCH/users/{id}:

{
    "accountState": "http://localhost:8080/accountStates/2"
}
Run Code Online (Sandbox Code Playgroud)

因此,您使用帐户状态的URI来引用要分配的资源

  • 有人可以解释为什么PUT不起作用吗? (4认同)