Database Reference
In-Depth Information
Optimistic locking
Optimistic locking is a strategy by which all the write requests (put, update, or delete) will
succeed only after ensuring that the client (performing the write request) and the server
have the same data version. If anyone else updates this data (which will change the data
version) then the client cannot perform this write operation. We will look at optimistic
locking in detail. Let's just add an attribute to the
BookEntity
class we saw previously:
@DynamoDBTable(tableName="Tbl_Book")
publicclassBookEntity {
private Longversion;
...
@DynamoDBVersionAttribute
public LonggetVersion() {
returnversion;
}
publicvoidsetVersion(Longversion) {
this.version = version;
}
}
Tip
The preceding class is not complete and shows only the new fields. For the complete struc-
ture, merge this with the older
BookEntity
class we saw previously.
We are adding an attribute to control the version-based locking named
version
. Then,
we create getters and setters, and then the getter of
version
is made to have a
@Dy-
namoDBVersionAttribute
annotation. These are the changes to be made in the
BookEntity
class.
Once we are done with this, then every write operation (save and delete) performed on
BookEntity
using the
DynamoDBMapper
class will check whether the client and the
server have the same version attribute. When a new item is put into the table, the value of
the version attribute will be
1
. For further update operation, this value will be incremented
by 1. Therefore, let us assume that our code retrieved the freshly put item from
Tbl_Book
with the values discussed in the
Java high-level API
section. Since this is a newly put item,
the version attribute will have the value
1
.