Sergii Bishyr
Sergii Bishyr

Reputation: 8651

Set the value for the field annotated with @CreationTimestamp

I have an entity that has a field annotated with @CreationTimestamp:

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

And now I have integration tests where I need to create a few entries with different createdAt timestamps timestamp. But when I set the value to one that I need and save it's getting overridden with the creating timestamp of the VM:

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

How can I insert the desired values for this field in my test env?

Upvotes: 3

Views: 4061

Answers (2)

Adhonores
Adhonores

Reputation: 108

Instead of using @CreationTimestamp annotation, you could remove it from the field and manage that date with a @PrePersist:

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

Of course, you can check whatever you want in there. You could still have an updatable=false on the field.

Upvotes: 1

Ahmed Abdelhady
Ahmed Abdelhady

Reputation: 759

I don't think it is possible to disable this behavior in an integration test as you need here.

However you can achieve the same using a workaround by setting the creation date after saving the entity, then save the entity once more to persist the new desired creation time.

This will work since @CreationTimestamp will only be triggered when saving the entity for the first time.

Upvotes: 1

Related Questions