Home > Blockchain >  Unable to update a document in Spring boot. Getting E11000 duplicate key error on mongorepository.sa
Unable to update a document in Spring boot. Getting E11000 duplicate key error on mongorepository.sa

Time:03-07

I am unable to perform update operation. Using spring boot with mongodb 3.4. On trying to save I am receiving the following kind of error :

WriteError{code=11000, message='E11000 duplicate key error collection

My domain class is extending another base domain class. My current findings are that the base domain class contains "private Long version" annotated with @Version. My guess is this is the field that's causing the issue. Things I have tried so far:

  • On initialising "private Long version = 0L;" my document updates just once, further updates gives the below error :

Something went wrong in service layer while updating the Employee.Cannot save entity 119794669940 with version 1 to collection Employee. Has it been modified meanwhile?

WriteError{code=11000, message='E11000 duplicate key error collection.

Some additional info:

  • I am not sending version in put body in any of the above cases I have tried so far(sending them with version key is giving the same error.

Anyone has any idea what's going on or how to proceed further?

CodePudding user response:

If you try to persist an entity with a null or 0 (for a primitive) it is considered a new entity.

If the version is anything else it is considered an update and the version is checked to be the version present in the database for optimistic locking.

You therefore need to set the version. Either include it in the body of the request or alternatively try to load the entity from the database and using the version from that if you find any. Of course, the latter version kind of defeats the idea of optimistic locking.

See also this answer about the handling of the version attribute if you are using Spring Data Rest

CodePudding user response:

I solved it by removing version field from @jsoniIgnoreProperties, it was added there. it resulted in ignoring the version field while fetching any document, and even while putting the version field in put body, it was sending it as "null". Removing it from the list of @jsonIgnoreProperties resulted in showing the version field in get body, and sending the same body while updating allowed me to update the document.

  • Related