I am trying to control concurrent access to same object in spring+jpa configuration. For Example, I have an entity named A. Now multiple processes updating the same object of A. I am using versioning field but controlling it but here is the issue: For example 2 processes reads the same entity (A) having version=1. Now one process update the entity and version gets incremented. when 2nd process tries to persist the object, Optimistic lock exception would be thrown. I am using spring services and repository to access the objects. Could you please help me here?
Asked
Active
Viewed 668 times
0
-
What is your desired outcome of the scenario that you described? What would you like to happen? – Krešimir Nesek Apr 22 '15 at 21:08
-
See answer here: http://stackoverflow.com/a/19456821/1356423 – Alan Hay Apr 23 '15 at 09:40
1 Answers
0
What's the problem then? That's how it's supposed to work.
You can catch the JpaOptimisticLockingFailureException and then decide what to do from there.
This, for example, would give a validation error message on a Spring MVC form:
...
if(!bindingResult.hasErrors()) {
try {
fooRepository.save(foo);
} catch (JpaOptimisticLockingFailureException exp){
bindingResult.reject("", "This record was modified by another user. Try refreshing the page.");
}
}
...

Neil McGuigan
- 46,580
- 12
- 123
- 152
-
I was expecting if hibernate or jpa itself can handle this exception and reload the object. – Apr 23 '15 at 13:41
-
@richyrich Reloading isn't always the best choice, so they leave that up to you. – Neil McGuigan Apr 23 '15 at 17:29