在EclipseLink中使用@Version批注跟踪对对象的最后更改 [英] Tracking last change to an object with @Version annotation in EclipseLink

查看:112
本文介绍了在EclipseLink中使用@Version批注跟踪对对象的最后更改的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

将JPA与EclipseLink结合使用,我想跟踪对实体实例进行的最新更新的时间戳.假设将其与乐观锁定结合起来很容易,我将实体定义如下:

Using JPA with EclipseLink, I would like to track the timestamp of the last update made to an entity instance. Assuming that this would be easy to combine with optimistic locking, I defined the entity as follows:

import javax.persistence.Version;
[...]

@Entity
public class Foo {
    @Id int id;
    @Version Timestamp lastChange;
    [...]
}

使用以下代码更新更改的对象:

Updating a changed object is done with the following code:

EntityManager em = Persistence.createEntityManagerFactory("myConfiguration");
em.getTransaction().begin();
em.merge(foo);
em.getTransaction().commit();

我希望每次提交对更改后的实例的更新时,都会将foo.lastChange设置为新的时间戳.但是,虽然字段LASTCHANGE在数据库中已更新,但它在对象本身中未更新.因此,再次尝试保存同一对象的第二次尝试失败,并显示OptimisticLockException.我知道EclipseLink允许在将版本字段存储在缓存中还是直接在对象中进行选择,并且确保将配置设置为IN_OBJECT.

I would expect that foo.lastChange would be set to the new timestamp each time an update to a changed instance is committed. However, while the field LASTCHANGE is updated in the database, it is not updated in the object itself. A second attempt to save the same object again thus fails with an OptimisticLockException. I know that EclipseLink allows to choose between storing the version-field in cache or directly in the object and I made sure that the configuration is set to IN_OBJECT.

一个明显的问题是:保存到数据库时,如何将foo.lastChange字段设置为更新的时间戳值?会

The obvious question is: How to get the foo.lastChange field set to the updated timestamp value when saving to the database? Would

foo = em.find(Foo.class, foo.id);

是唯一的选择吗?我怀疑一定有更简单的方法.

be the only option? I suspect there must be a simpler way to this.

推荐答案

merge不会修改其参数.它将状态从其参数复制到其参数的附加版本,并返回附加版本.因此,您应该使用

merge does not modify its argument. It copies the state from its argument to the attached version of its argument, and returns the attached version. You should thus use

foo = em.merge(foo);
// ...
return foo;

这篇关于在EclipseLink中使用@Version批注跟踪对对象的最后更改的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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