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)
-
最初插入一个
person
daenerys
,version
为0
。 -
加载刚插入的数据,
tmp
。version
还是0
。 -
更新
version = 0
的daenerys
,更新lastname
,save后version
变为1
。 -
现在来更新,会抛出
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
出处:https://www.cnblogs.com/xiaoqi/p/spring-data-optimistic-lock.html
版权:本文采用「署名-非商业性使用-相同方式共享 4.0 国际(欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文链接) 」知识共享许可协议进行许可。
分类:
java编程
标签:
Spring Boot
, MongoDB
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
2018-04-16 新型前端开发工程师的三个境界 后端开发工程师如何快速转前端