I have DB tables representing Employees and Departments. The server side(JavaEE) contains JPA entities representing the same.
The client is a standalone client and communicates with the server using DTOs. In my case, a single DTO contains both the Employee and Dept details.
I want to implement Optimistic locking using the Version annotation on these entities, but there is an issue: When the client send the DTO with the updated values to the server method(webservice), the server method creates entities using the values in the DTO and then it finds the entity using the find() method on JPA and then calls update(). There is not much gap between find() and update().
But the issue is that the value coming from the DTO itself might be stale. Since I am using standalone client, I do not have the context of the server's JPA entities. JPA itself cannot find that the value is old (because the version between find() and update() matches) and overwrites the entity with stale data. Is there a way to solve this issue?
find
before theupdate
? Doesn't your DTO contain all the information that is needed to perform an update?find
can't prevent that you try to update stale data, because some other process might do an update between yourfind
andupdate
. The only defence against that is to perform the check together with the update in an atomic action.