15

I'm going through Spring Data MongoDB - Reference Documentation and I'm finding the examples to be a bit too simplistic.

In particular I'm trying to understand how to handle stale data in concurrent environments. For instance, imagine I have the following entity:

public class Person {

    private final String username;
    private final String firstname;
    private final String lastname;

    [...]

}

Now if I use CrudRepository to save/update/remove my entities, then imagine a scenario in which two threads retrieve the same entity, one of them removes it, and the other one updates its lastname field. If the delete call completes before the save call then my entity will be removed and then re-created, when the expected behaviour would be for the save operation to fail.

So far I've seen two options for getting around this issue:

  1. Use @Version annotation. Could not find any documentation saying Spring Data supports optimistic locking in MongoDB using versioned documents. If anyone can point me to a link it'd be appreciated.
  2. Use MongoOperations.findAndModify and fail if it returns null. The downside to this approach is that I can no longer implement my repository API to have "get entity" and "save updated entity" kind of semantics. e.g.:

    User user = userRepository.findByUsername("uniqueUsername");
    user.setLastName("Archer");
    userRepository.update(user);
    

I would have to push some of this to the repository I guess:

userRepository.updateLastname("uniqueUsername", "Archer");

But I'm a little bit worried my repository interfaces will grow uncontrollably if every type of update I want to do requires a new method.

I realise I haven't actually stated a question yet, so here it goes: what's the best-practice for designing an application using Spring Data for MongoDB?

1 Answer 1

15

Using @org.springframework.data.annotation.Version on a property should do the trick. I've created DATAMONGO-1275 to improve the documentation on that.

Sign up to request clarification or add additional context in comments.

3 Comments

If i understand it correctly this will throw an OptimisticLockException only when updating right? Is it possible to also support delete?
It would have been more helpful if the documentation specified the fully qualified path of the Version annotation to use, ended up here to verify that.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.