'mongoDb spring data @Version annotation

I am new to the @Version annotation and trying to understand how to use it.

Lets say I have a document Customer and Repository as follows:

@Data
public class Customer {

    @Id
    private String id;

    private String firstName;
    private String lastName;
    @Version
    private Long version;

Reporitory as follows:

public interface CustomerRepository extends MongoRepository<Customer, String> {

    public Customer findByFirstName(String firstName);
    public List<Customer> findByLastName(String lastName);

}

Lets say I have the following scenario:

  1. Create a new customer - version is 0
  2. Update the above customer - version is updated to 1

When I build my customer document for update and leaves version null the latter fails with the following error:

code=11000, message='E11000 duplicate key error collection: payment.customer index: _id_ dup key: 
...

I think because the value of version is null on update it is treating it as new and thus duplicate key error.

When I set the version to the value already saved in db which is 0, save is OK and version is incremented to 1 after update.

I have seen online resources stating that the version should not be set programmatically and framework should manage it.

So my question is do I need to set the value of version to 0 prior of update or I am not doing it correctly?

Thanks in advance



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source