1

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.

chb
  • 111
  • 1

1 Answers1

0

There are two approaches to handle the problem: Pessimistic and Optimistic locking.

I would not use pessimistic locking at the application level, but rather handle the visibility of the data to multiple transactions using the database isolation level. I'm assuming here that you are using a RDMS. Read about the concurrency control mechanism of your database and choose an appropriate isolation level based on your application requirements. PostgreSQL documentation is a great resource.

Then you can use optimistic locking to take care of the Lost Update Problem. I recommend you to read this excellent resource about the subject.

Diego Marin Santos
  • 1,923
  • 2
  • 15
  • 29