代码之家  ›  专栏  ›  技术社区  ›  Sergii Bishyr

设置用@CreationTimestamp注释的字段的值

  •  0
  • Sergii Bishyr  · 技术社区  · 7 年前

    我有一个实体,它有一个用 @CreationTimestamp :

    @Entity
    @Table(name = "foo")
    class Foo {
      ...
      @Column
      @CreationTimestamp
      private Instant createdAt;
    }
    

    createdAt 时间戳。但当我将该值设置为我需要的值并保存时,它将被VM的创建时间戳覆盖:

    Foo foo = new Foo();
    foo.setCreatedAt(Instant.MIN);
    foo = fooRepo.save(foo);
    foo.getCreatedAt(); // equals to the creation time
    

    0 回复  |  直到 7 年前
        1
  •  1
  •   Ahmed Abdelhady    7 年前

    我认为不可能在集成测试中禁用此行为。

    但是,您可以通过在保存实体后设置创建日期,然后再次保存实体以保持新的所需创建时间,从而使用变通方法实现相同的效果。

    从那时起,这将起作用 @CreationTimestamp 仅在第一次保存实体时触发。

        2
  •  1
  •   Adhonores    7 年前

    而不是使用 @CreationTimestamp 注释,您可以将其从字段中删除,并使用 @PrePersist :

    @PrePersist
    void onCreate() {
        this.setCreatedAt(Instant.now());
    }
    

    updatable=false 在球场上。