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:

提供@Version注解,用來標識版本,保存、刪除等操作會驗證version,不一致會拋出OptimisticLockingFailureException

來看一個例子:

@Document
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)

daenerys.setLastname("Targaryen");
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.

作者:Jadepeng
出處:jqpeng的技術記事本--http://www.cnblogs.com/xiaoqi
您的支持是對博主最大的鼓勵,感謝您的認真閱讀。
本文版權歸作者所有,歡迎轉載,但未經作者同意必須保留此段聲明,且在文章頁面明顯位置給出原文連接,否則保留追究法律責任的權利。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM