Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 430
Sergii Bishyr Avatar asked Nov 02 '25 21:11

Sergii Bishyr


1 Answers

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.

like image 127
Ahmed Abdelhady Avatar answered Nov 04 '25 11:11

Ahmed Abdelhady