How do I prevent a concurrency in Spring transactional?
The situation is two requests in parallel to the method below:
@Transactional
public save() {
Optional<Example> result = repository.findById(1);
if(!result.isPresent()) {
Example exemple = new Exemple();
exemple.setParam1(1);
exemple.setParam2(1);
exemple.setParam3(1);
exemple.setParam4(1);
exemple.setParam5(1);
exemple.setParam6(1);
exemple.setParam7(1);
exemple.setParam8(1);
repository.save(exemple);
}
}
So, for exemple, the second request passes through the "ifPresent" verification before the first request ends and commit. Causing unexpected behavior and saving the object twice.
Do I need to use the @EnableTransactionManagement? Do I need to use some value in @Transactional?