How to use optimistic locking using Spring Data MongoDB?

I am surviving Spring Data MongoDB - help documentation , and I find the examples are too simplistic.

In particular, I am trying to understand how to handle obsolete data in parallel environments. For example, imagine that I have the following object:

public class Person { private final String username; private final String firstname; private final String lastname; [...] } 

Now, if I use CrudRepository to save / update / delete my objects, imagine a scenario in which two threads retrieve the same object, one of them deletes it, and the other updates its lastname field. If the delete call completes before the save call, then my object will be deleted and then recreated when the expected behavior is executed for the save operation.

So far, I have seen two solutions to this problem:

  • Use @Version annotation. Could not find documentation stating that Spring Data supports optimistic locking in MongoDB using document versions. If someone can point me to a link, it will be appreciated.
  • Use MongoOperations.findAndModify and fail if it returns null . The disadvantage of this approach is that I can no longer implement my repository API in order to get the semantics of “get entity” and “save updated entity”. eg:

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

I would need to push some of this into the repository, which I assume:

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

But I'm a little concerned that the repository interfaces will grow uncontrollably if a new method is required for each type of update I want to do.

I understand that in fact I have not asked a question yet, so here it is: what is best suited for developing an application using Spring data for MongoDB?

+5
source share
1 answer

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

+5
source

All Articles