Spring Data (or JPA) - How to update entity but don't insert if it doesn't exist

Viewed 517

I have a situation where I need to be able to update an entity but be able to throw an exception if it doesn't exist.

The best I could come up with:

if (!authorRepository.existsById(1L)) {
    throw new Exception("entity doesn't exist yet!");
} else {
    authorRepository.save(entity);
}

Are there other ways? It doesn't seem like JPA provides a way to only do updates, EntityManager.merge() behaves like create or update.

1 Answers

Save method is auto detect in spring boot hibernate and check the id of entity does have exist, update it

Related