@Version
注解在 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.
但我仍然不确定它是如何工作的。
同样来自以下几行:
You should consider version fields immutable. Changing the field value has undefined results.
这是否意味着我们应该将我们的版本字段声明为final
?
最佳答案
But still I am not sure how it works?
假设一个实体 MyEntity
有一个带注释的 version
属性:
@Entity
public class MyEntity implements Serializable {
@Id
@GeneratedValue
private Long id;
private String name;
@Version
private Long version;
//...
}
更新时,带有 @Version
注释的字段将递增并添加到 WHERE
子句中,如下所示:
UPDATE MYENTITY SET ..., VERSION = VERSION + 1 WHERE ((ID = ?) AND (VERSION = ?))
如果 WHERE
子句未能匹配记录(因为同一实体已被另一个线程更新),则持久性提供程序将抛出 OptimisticLockException
。
Does it mean that we should declare our version field as final
不,但您可以考虑让 setter protected ,因为您不应该调用它。
关于Java - JPA - @Version 注释,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2572566/