I am working on a warehouse management system, using JPA 2.0 – EclipseLink and I have come across the need to implement concurrent transactions, currently I am implementing a timestamp difference to validate the last time the quantities are altered: added, removed, transferred.
This strategy seems a bit flawed, and requires a lot of manual verification’s, that may create bugs, are there alternative methods of doing this that are provided by the JPA framework?
As far as I understand you are trying to implement an optimistic locking strategy with timestamps.
JPA provides out of the box an optimistic locking mechanism with the help of a version field. Basically you have a version field (
short,int,longorTimestamp) in your entities that is incremented/set on every modification of the entity.If an entity has a different version at save time than the version it had at load time an
OptimisticLockingExceptionis thrown meaning that another user/thread modified the entity in between. You can catch this exception and decide what do:It depends on the usecase.
See also: oracle javaee 6 tutorial on optimistic locking