Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how spring data jpa repository.save only do update

Tags:

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

like image 922
Awakening Avatar asked Feb 10 '15 04:02

Awakening


People also ask

How do I stop Spring data JPA from doing a select before a save ()?

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!!

How does save work in JPA?

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.

What does save and flush do in JPA?

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.


1 Answers

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:

  1. By default, Spring inspects the Id-Property (@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.
  2. Another way to take better control of this is by implementing Persistable. For entities that implement Persistable, Spring will call isNew(…) method to figure out if it must be Inserted or Updated.
like image 200
Manish Maheshwari Avatar answered Oct 19 '22 23:10

Manish Maheshwari