JPA中的并发(陈旧数据)问题 [英] concurrency (stale data) problem in JPA
问题描述
假设我有以下签名的方法
Let's say I have methods with following signature
Object getData(int id) {
//create a entity manager
//get data frm db
//return data
}
updateData() {
Object obj = getData(id)
//get entity manager
//start transcation tx
//update
//commit tx
}
现在会引起并发问题吗?在最坏的情况下,数据是否会过时?例如。
如果我 getData
并且在我更新时,如果有人更新数据,我的 updateData
将会有陈旧的数据?
现在可以使用以下内容:我能解决问题吗?
Now will it cause concurrency issue? Can data be stale in worst case? E.g.
if I getData
and by the time I update, if someone updates the data will my updateData
will have stale data?
Now can i use following:Will i solve the problem?
Object getData(int id,Entitymanager em) {
//get data frm db using em
//return data
}
updateData() {
Object obj = getData(id)
//get entity manager em
//start transcation tx
//getdata using getData(id,em)
//commit tx
}
推荐答案
是的,可能会发生这种情况。
Yes, that can happen.
如果您获得实体(版本1),其他人修改它(创建版本2),然后您修改版本1并保存它,版本2中的任何更改都将丢失。
If you get an entity (version 1), someone else modifies it (creating version 2), then you modify version 1 and save it, any changes in version 2 will be lost.
要阻止这种情况发生,请通过向实体添加@Version属性来使用乐观并发。如果在get和update之间发生了提交,则会抛出异常。在这一点上,您可以选择最佳选择来处理它。
To stop that from happening, use optimistic concurrency by adding a @Version attribute to your entity. If a commit has occurred between your get and update, an exception will be thrown. At the point you can choose your best option to deal with it.
这篇关于JPA中的并发(陈旧数据)问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!