0

my situtation is as follows:

I have @Entity class Ingredient in my Spring JPA Project. I would like to implement a method performing delete operation on DB record by record Id public boolean deleteIngredient(String id) and if possible avoid handling exceptions for non-existent Ids.

Unfortunately the only recommendations I can find in this area are based on the fact of querying by Id before deleting record e.g.

ingredientRepository.findById(id).ifPresent(x -> ingredientRepository.deleteById(id));

or

        if(ingredientRepository.existsById(id)){
            ingredientRepository.deleteById(id);
        }

which I believe are prone to race conditions (other thread may delete record after this one queries for existence. Is the best approach really just wrapping it in a try-catch block and handling EmptyResultDataAccessException in case record with given Id does not exist?

Veidt
  • 33
  • 4

1 Answers1

0

If you are using JPA, you need the entity to be marked for deletion in the persistence context (e.g. not in the Database). Keep in mind JPA Repository follows the ORM paradigm and is not acting on the record directly.

Any race conditions will be handled on the persistence context level.

If you use @Transactional and you will be safe.

Also if you don't want the explicit error thrown by deleteById, when the ID is not known to the EntityManager, consider using delete (which will just return with no exception being thrown in case the ID is unknown).

hovanessyan
  • 30,580
  • 6
  • 55
  • 83
  • So, I have read more about @Transactional annotation, and if I got this right what it does is it basically wraps whole method into one DB transaction so the method is safe from any race-conditions as no mutation of DB state can occur during its execution? – Veidt Jun 17 '22 at 14:52
  • execution of transactions depends on the configured transaction isolation levels (so no - the DB is still not safe). the default implementation of JPA repository (check the linked source implementation) is already having @transactional on every method. So in certain cases you don't need to set it yourself. – hovanessyan Jun 17 '22 at 19:05