How spring-data-jpa repository.save
only do update
but NOT create new one if primary key is not found.
Currently, repository.save() will create a now record in my database if not found
An easy way is to make your Entity implements Persistable (instead of Serializable), which will make you implement the method "isNew". The Persistable entity solution was amazing!!
The save operation performs a merge on the underlying EntityManager . This on its own doesn't perform any SQL but just returns a managed version of the entity. If that isn't already loaded into the EntityManager it might do this or it might identify the entity as a new one and make it a managed entity.
The saveAndFlush() Method Unlike save(), the saveAndFlush() method flushes the data immediately during the execution. This method belongs to the JpaRepository interface of Spring Data JPA.
Repository.save()
is a dual purposed method for Insert as well as Update
There are two mechanisms used by Spring to decide if it must use Insert or Update on an entity:
@Id
) of the entity, to figure out if the entity is new or not. If the identifier property is null, then the entity is treated as new, else not new.Persistable
. For entities that implement Persistable
, Spring
will call isNew(…)
method to figure out if it must be Inserted or Updated.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