8

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?

Centurion
  • 14,106
  • 31
  • 105
  • 197
florind
  • 361
  • 4
  • 12
  • Possible duplicate of [Hibernate: How to fix "identifier of an instance altered from X to Y"?](http://stackoverflow.com/questions/4179166/hibernate-how-to-fix-identifier-of-an-instance-altered-from-x-to-y) – Makoto Jan 12 '16 at 23:05
  • @Makoto, I think the other question is about changing the PK of an owning entity, my issue is about changing a child relationship where no cascading is defined between User and AccountState. – florind Jan 13 '16 at 09:40

1 Answers1

11

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

Mathias Dpunkt
  • 11,594
  • 4
  • 45
  • 70
  • Hey Mathias, I am having the same problem but due to various reasons the 'accountState' in our instance is not exported. Is there a way to do it without it exported? – pasquers Nov 17 '16 at 17:37
  • @pasquers I don't think so - I think you would have to create a custom controller for the update and add a link to that to your owning resource – Mathias Dpunkt Nov 17 '16 at 20:51