I have the following issue with a REST Application I am trying to develop: In one of my service classes, I have a method to delete an object from my database while notifying the user if that resource does not exist, similar to the following:
@Transactional
public class MyEntityService {
    @Autowired
    private MyEntityrepository repo
    public void delete(String name) {
        MyEntity e = repo.findByName(name)
                      .orElseThrow(() -> new ResourceNotFoundException(name));
        repo.delete(e);
    }
}
Is there any convenient way for me to make certain that no to calls to the delete method overlap with the same entity as their target? I considered using the EntityManagers lock method (https://www.objectdb.com/api/java/jpa/EntityManager/lock_Object_LockModeType), like so:
MyEntity e = repo.findByName(name)
              .orElseThrow(() -> new ResourceNotFoundException(name));
try {
    em.lock(e, LockModeType.PESSIMISTIC_WRITE)
} catch ( PessimisticLockException e) {
    //Handle somehow
}
repo.delete(e);
But I am not sure if this is the right way, or what happens should I try to delete a parent entity that cascades its deletion to the locked entity.
 
    