【问题标题】:Tracking last change to an object with @Version annotation in EclipseLink在 EclipseLink 中使用 @Version 注释跟踪对象的最后更改
【发布时间】:2011-12-23 13:47:48
【问题描述】:

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

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

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

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

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

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

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

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

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

【问题讨论】:

    标签: jpa eclipselink


    【解决方案1】:

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

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

    【讨论】:

      猜你喜欢
      • 2013-03-18
      • 2012-01-02
      • 2013-03-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-11-23
      相关资源
      最近更新 更多