Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 777
florind Avatar asked Jan 12 '16 22:01

florind


People also ask

What is difference between JpaRepository and CrudRepository?

Crud Repository is the base interface and it acts as a marker interface. JPA also provides some extra methods related to JPA such as delete records in batch and flushing data directly to a database. It provides only CRUD functions like findOne, saves, etc. JPA repository also extends the PagingAndSorting repository.

What is @manytoone in spring boot?

The many-to-one mapping or association means that one parent record can have multiple child records. In other words, multiple records of a table can associate themselves with a common record in another table. For example, The relationship of Account to Branch entities follows the Many to One mapping.


1 Answers

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

like image 121
Mathias Dpunkt Avatar answered Sep 19 '22 14:09

Mathias Dpunkt