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?
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With