Spring Data Mongodb 乐观锁

Spring Data 针对mongodb提供了乐观锁实现:

The @Version annotation provides syntax similar to that of JPA in the context of MongoDB and makes sure updates are only applied to documents with a matching version. Therefore, the actual value of the version property is added to the update query in such a way that the update does not have any effect if another operation altered the document in the meantime. In that case, an OptimisticLockingFailureException is thrown. The following example shows these features:



class Person {

  @Id String id;
  String firstname;
  String lastname;
  @Version Long version;

Person daenerys = template.insert(new Person("Daenerys"));                            (1)

Person tmp = template.findOne(query(where("id").is(daenerys.getId())), Person.class); (2)

template.save(daenerys);                                                              (3)

template.save(tmp); // throws OptimisticLockingFailureException                       (4)
  1. 最初插入一个person daenerysversion0

  2. 加载刚插入的数据,tmpversion还是0

  3. 更新version = 0daenerys,更新lastname,save后version变为1

  4. 现在来更新,会抛出OptimisticLockingFailureException, 提示操作失败。


Important Optimistic Locking requires to set the WriteConcern to ACKNOWLEDGED. Otherwise OptimisticLockingFailureException can be silently swallowed.
Note As of Version 2.2 MongoOperations also includes the @Version property when removing an entity from the database. To remove a Document without version check use MongoOperations#remove(Query,…​) instead of MongoOperations#remove(Object).
Note As of Version 2.2 repositories check for the outcome of acknowledged deletes when removing versioned entities. An OptimisticLockingFailureException is raised if a versioned entity cannot be deleted through CrudRepository.delete(Object). In such case, the version was changed or the object was deleted in the meantime. Use CrudRepository.deleteById(ID) to bypass optimistic locking functionality and delete objects regardless of their version.


posted @ 2020-04-16 14:17  JadePeng  阅读(970)  评论(0编辑  收藏  举报