Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you implement a coarse-grained optimistic lock in REST?

I have implemented optimistic locking for my REST resources that have 1-to-1 mapping to database tables by passing back a version number which was in the GET back through to the PUT call. If the version number changed in the database between the time I did the GET and the PUT, then an optimistic lock exception has occurred. Pretty simple design.

Now, how do I do the same for composite REST resources that map to multiple database tables? I'd like to not have to pass back multiple version fields (one for each data table that relates to the composite resource). A simplistic example of a composite resource would be /FooBar where /Foo and /Bar are non-composite resources.

I'm basically looking for an example of the REST implemetation of Fowler's Coarse Grained Locking pattern: http://martinfowler.com/eaaCatalog/coarseGrainedLock.html

like image 821
BestPractices Avatar asked Feb 03 '13 21:02

BestPractices


People also ask

How do you implement optimistic locking?

In order to use optimistic locking, we need to have an entity including a property with @Version annotation. While using it, each transaction that reads data holds the value of the version property. Before the transaction wants to make an update, it checks the version property again.

How do you handle optimistic lock exception?

To resolve this error we have two ways: Get the latest object from the database and set the old object values if you need those values to be persisted to the new object and merge it. For the old object set the latest version from Database.

What is optimistic locking in database?

Optimistic locking is a technique for SQL database applications that does not hold row locks between selecting and updating or deleting a row. The application is written to optimistically assume that unlocked rows are unlikely to change before the update or delete operation.

How can we avoid optimistic locking in JPA?

The OptimisticLockType. NONE disables the default optimistic locking mechanism for the TestEntity . However, that would only be useful if you inherited the @Version property from a base class which is annotated with @MappedSuperclass or @Inheritance .


1 Answers

This is what the ETag header was designed for. A very common way to implement it is to produce your response payload, make a hash of it (it doesn't have to be secure, just low-collision), and then use that hash as the value of the ETag. Note that this approach is ignorant of how many sources are involved in producing the response.

The client then sends the received ETag back in an If-Match header, which the server can use to check the freshness of the request.

like image 133
fumanchu Avatar answered Sep 20 '22 05:09

fumanchu