Search code examples
couchbasespring-data-couchbase

Correct way to use @Version


Can someone please tell me how exactly this @Version works for locking? Because I don't see the version field is saved in the Couchbase, but when I retrieve it, this field is populated with some random value.

Should I manually set this value when save? For example, I have a POST and PUT endpoint. if I don't set the version with the existing version number, I will get a DocumentAlready exist error. But for the POST, it is ok the save without setting the version (I guess it will automatically generate the new random value for the new record).


Solution

  • In couchbase, each document has some metadata associated with it, ex:

    "cas": 1571854188210290688,
    "expiration": 0,
    "flags": 0,
    "id": "path::3c23b8a1-55ca-4cd9-a3cc-d6641abf1adc",
    "type": "json"
    

    This data is usually transparent to you if you are using Couchbase with Spring Data, but you can inject it in a field if you need to. That is exactly what happens with the @Id annotation. You don't need to worry with the @Version unless you want to do some optmistic/pessimistic locking.