Java - JPA - @Version 注释 [英] Java - JPA - @Version annotation

查看:24
本文介绍了Java - JPA - @Version 注释的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

@Version 注释在 JPA 中是如何工作的?

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 有一个带注释的 version 属性:

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.

这是否意味着我们应该将我们的 version 字段声明为 final

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆