Optimistic lock in RESTful application

At work, we are developing a RESTful application in which the data layer will be processed by Hibernate. But we do not know how to handle updates for entities.

We plan to do the following:

1) the client requests the object by identifier
2) Hibernate loads the object, the requested fields (always with the version) are copied to the DTO, which is converted to JSON and sent to the client
3) The client manages some fields and sends the object (with the version number) back to the server.
4) The server receives JSON, which is converted to DTO.
5) The corresponding object is loaded from Hibernate, and the details of the DTO are copied to the object.

=> An entity is always overwritten, even if a client version number has been set. Does this mean that we always need to check the client version number on the version number of the downloaded instance, and not on Hibernate?

In a typical session application, a separate instance is stored in HttpSession. Whenever the client updates the object, the instance is retrieved from the HttpSession, and some attributes are updated. Whenever Hibernate updates, an ObjectStaleException is thrown if the version number is <current version number.

The problem here is that we do not have an Http session because we are trying to be RESTful.

Is there a general solution for optimizing optimized locking in RESTful applications instead of checking version numbers myself?

+4
source share
1 answer

Your strategy is good. Just copy the version number coming from the client into the loaded object (or use merge() , which will do the same), and when Hibernate discards the object, if the version number has been increased, you will have an optimistic blocking exception.

You do not need to check anything yourself. Hibernate does the check for you.

+2
source

Source: https://habr.com/ru/post/1496392/


All Articles