title: How to use document locks to prevent external modification of records during Spring Data Mongodb transactions
body: <p>I have a question regarding Spring Data Mongo and Mongo Transactions.</p>
  
  <p>I have successfully implemented Transactions, and have verified the commit and rollback works as expected utilizing the Spring @Transactional annotation.</p>
  
  <p>However, I am having a hard time getting the transactions to work the way I would expect in the Spring Data environment.</p>
  
  <p>Spring data does Mongo -> Java Object mapping.  So, the typical pattern for updating something is to fetch it from the database, and then make modifications, then save it back to the database.   Prior to implementing transactions, we have been using Spring's Optimistic Locking to account for the possibility of updates happening to a record between the fetch and the updated.  </p>
  
  <p>I was hoping that I would be able to not include the optimistic locking infrastructure for all of my updates once we were able to use Transactions.  So, I was hoping that, in the context of a transaction, the fetch would create a lock, so that I could then do my updates and save, and I would be isolated so that no one could get in and make changes like previously.  </p>
  
  <p>However, based on what I have seen, the fetch does not create any kind of lock, so nothing prevents any other connection from updating the record, which means it appears that I have to maintain all of my optimistic locking code despite having native mongodb transaction support.</p>
  
  <p>I know I could use mongodb findAndUpdate methods to do my updates and that would not allow interim modifications from occurring, but that is contrary to the standard pattern of Spring Data which loads the data into a Java Object.  So, rather than just being able to manipulate Java Objects, I would have to either sprinkle mongo specific code throughout the app, or create Repository methods for every particular type of update I want to make.</p>
  
  <p>Does anyone have any suggestions on how to handle this situation cleanly while maintaining the Spring Data paradigm of just using Java Objects?</p>
  
  <p>Thanks in advance!</p>