I am using Spring-Boot and JPA.
For saving and also updating a record there is the one method save of CrudRepository.
I use a generated long id for primary key of my record.
Now I need to update a already existing record. That will fail with an duplication exception if the primary key id does not match the value that is already in the database. If no id is given JPA would assume an insert and that fails because the old record already exists.
So what is the best strategy for that?
I do not want to look for the id of the existing record before doing a save for updating my record.
Is there some default value for id that I an use for marking it for update instead of insert?
CodePudding user response:
I don't think Hibernate has such functionality. Some databases support this with their native capabilities (insert ignore
in MySQL or on conflict do nothing
in Postgres), but you'd have to write SQL yourself. And some databases don't have this feature at all.
Probably, the only way to do this with Hibernate is to handle constraint violation exceptions. Note though if it happens, you may not be able to proceed with the transaction/session since Hibernate warns you that Session/EntityManager can't be further used reliably if it threw an exception.
CodePudding user response:
The concept in case of save() is, if the entity instance is not managed, it will insert the record. In case of saveOrUpdate, if the Id is there, it will update else insert
Otherwise, to update a record, you will have to fetch the record first, this will make it a Managed Entity and then you can update the field values and update. Record can not be updated if the Entity instance is not in managed state. (Exceptions are in Detached state with merge() or saveOrUpdate with id).
One Possible way: Using HQL without id will update all the records but if you have any other unique field then it shall be possible using HQL.