Reputation: 3322
I have been facing this issue for a while.
@Service
public class SomeService{
@Autowired
private Repo repo;
@Transactional
public void update(int id){
repo.findById(id).ifPresent(entity -> entity.setName(entity.getName() + "-name"));
}
}
My problem is that - often times same id is passed by 2 different threads to update the entity. I see only the last update in the entity.
That is -
entity.getName()
by default will return some
.
the expected result is - some-name-name
but what i see in the end is some-name
.
The problem seems to be findbyId is executed at the same time by 2 different threads and leave that entity in this state.
How to handle this?
Upvotes: 0
Views: 565
Reputation: 24482
You should use optimistic locking with retry to make sure both updates end up committing.
Have a look at this question: Spring Optimistic Locking:How to retry transactional method till commit is successful
The key is to use Spring Retry and capture the optimistic locking exception.
Upvotes: 1