java – How to do update correctly in spring data jpa?

Question:

I understand that according to the spring data paradigm we have a set of entities and only one save method for update and insert . But what if I don't need to add a new record if there is no such primary key? Make two requests (see that such a record already exists and then update (but it can be expensive))? Or is it worth doing @Query for update (which seems like a very crutch)?

Answer:

Check before save:

SomeEntity entity = someEntityRepository.findOne(id);
if(entity != null){
   entity.setSomeValue(value);
   someEntityRepository.save(entity);
} 
Scroll to Top