Java - JPA - @Version注释 [英] Java - JPA - @Version annotation
问题描述
JPA中的 @Version
注释如何工作?
How does @Version
annotation work in JPA?
我找到了各种答案,摘录如下:
I found various answers whose extract is as follows:
JPA使用实体中的版本字段来检测对同一数据存储记录的并发修改。当JPA运行时检测到同时修改同一记录的尝试时,它会向尝试最后提交的事务抛出异常。
JPA uses a version field in your entities to detect concurrent modifications to the same datastore record. When the JPA runtime detects an attempt to concurrently modify the same record, it throws an exception to the transaction attempting to commit last.
但是我仍然不确定它是如何工作的。
But I am still not sure how it works.
同样来自以下几行:
您应该认为版本字段是不可变的。更改字段值具有未定义的结果。
You should consider version fields immutable. Changing the field value has undefined results.
这是否意味着我们应该将我们的版本字段声明为 final
?
Does it mean that we should declare our version field as final
?
推荐答案
但我仍然不确定它是如何工作的?
But still I am not sure how it works?
假设一个实体 MyEntity
有一个带注释的版本
属性:
Let's say an entity MyEntity
has an annotated version
property:
@Entity
public class MyEntity implements Serializable {
@Id
@GeneratedValue
private Long id;
private String name;
@Version
private Long version;
//...
}
更新时,用 @Version
注释的字段将递增并添加到 WHERE
子句中,如下所示:
On update, the field annotated with @Version
will be incremented and added to the WHERE
clause, something like this:
UPDATE MYENTITY SET ..., VERSION = VERSION + 1 WHERE ((ID = ?) AND (VERSION = ?))
如果 WHERE
子句无法匹配记录(因为同一实体已被另一个线程更新),然后持久性提供程序将抛出 OptimisticLockException
。
If the WHERE
clause fails to match a record (because the same entity has already been updated by another thread), then the persistence provider will throw an OptimisticLockException
.
这是否意味着我们应该将我们的版本字段声明为最终
Does it mean that we should declare our version field as final
否但你可以考虑将setter保护为你不应该叫它。
No but you could consider making the setter protected as you're not supposed to call it.
这篇关于Java - JPA - @Version注释的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!