user1354825
user1354825

Reputation: 1521

Cosmos DB SQL API - Optimistic concurrency control - usage of etag

I am using CosmosRepository( not ReactiveCosmosRepository) and i want to handle concurrency using the "_etag" property. I added the "_etag" property to my document as :-

class User {

@Id
private String id;

@JsonProperty("_etag")
private string tag;
}

When i do the below :

document.setTag("ABCD");
repository.save(document)

The document in cosmos db looks like :-

{
 "id" : " some random uuid ",
 "_etag" : " again some random uuid",
 "_ts" : "123123123"
 "_rid": "random string"
 "_self": "again random strings"
 "_attachments" : "attachments/"
}

BUT i was expecting _etag to look like :

{
...
 "_etag" : "ABCD" 
...
}

Because i did document.setTag("ABCD")

When i took the db-generated _etag and added it in my PUT methods (obviously to update the record) , the save(update) was successful even if the tag did not match.

Do i need additional configuration ? Won't a simple repository.save() with etag field defined in the document suffice ?

Upvotes: 1

Views: 6019

Answers (2)

anfeldma-ms2
anfeldma-ms2

Reputation: 109

https://github.com/Azure-Samples/azure-cosmos-java-sql-api-samples/blob/master/src/main/java/com/azure/cosmos/examples/documentcrud/sync/DocumentCRUDQuickstart.java#L210

Jcoder you are on the right track in using the above sample as the basis of your solution.

Spring Data Azure Cosmos DB is built on top of the Azure Cosmos DB Java SDK which is where CosmosClient comes from. I understand, you are trying to accomplish the above without using the Java SDK and CosmosClient directly. But actually that is what we recommend you to do. In pom.xml make sure to pull in both Spring Data Azure Cosmos DB and Azure Cosmos DB Java SDK.

For another example of using both the Spring Data connector and the underlying Java SDK simultaneously, see "Custom query execution" at this link

https://learn.microsoft.com/en-us/azure/developer/java/spring-framework/how-to-guides-spring-data-cosmosdb

Upvotes: 2

Mark Brown
Mark Brown

Reputation: 8763

You cannot actively set the value for etag in Cosmos DB. This is handled for you automatically. You only need to insert, replace, or upsert the item for it to be set.

Upvotes: 2

Related Questions