handling lost update problem happening with one thread updating a resource at a time

so i got this quite an interesting problem where i got a piece of code that edits a entity
there is one class and a bunch of other classes that inherit it
the superclass has a version field for optimistic locking
all subclasses are stored in the same jpa repository

the lost update/stale data problem comes when sending an update command
example scenario

employee gets updated salary to 3000 but the request will sent later
employee gets updated salary to 5000 but the request is sent immediately

so the employee gets 3000 salary even though he was supposed to have 5000

i was thinking of comparing the version of the entity and the version thats sent in the command but that generates race condition

example code

    @Transactional
    public Dto edit(long id, EditCommand command) {
        try {
            Subclass subclass = repository.findWithLockingById(id)
                    .orElseThrow();
//            if (command.getVersion() != subclass.getVersion()) {
//            } generates race condition
            service.update(command, subclass);
            return mapper.mapToDto(subclass);
    }
Was this page helpful?