Why @UpdateTimestamp is setting a value by default on entity creation?
Asked Answered
R

1

6

I have an entity with a field to save the date when the entity was updated. I'm using the annotations below:

@Temporal(TemporalType.TIMESTAMP)
@UpdateTimestamp
@Column(name = "updated_at", nullable = true)
private Date updatedAt;

I want updatedAt in null as default value but I have as default value the same date when the entity was created.

In my @Service class I save the entity like this:

visitorRepository.saveAndFlush(visitor)

There is a way to save my updatedAt in null as default value using @UpdateTimestamp?

Reflective answered 10/3, 2021 at 23:37 Comment(6)
Check de documentation deeply, but Im 99% sure that is not posible. When you are saving, really it is a type of update. If you have, for example, 2 columns: one for update time stamp and another for insert time stamp, when you save an object and no update it after, both will have same value,Lonee
Is exactly what is happening, createdAt and updatedAt have the same value after entity creation. createdAt have the @CreationTimestamp annotation.Reflective
@UpdateTimestamp uses GenerationTiming.ALWAYS so a value is always generated (either INSERT or UPDATE). Not sure if will work, but perhaps try @Column(... insertable = false).Interne
Is not bad behavior. If you have same value in both columns (insert and update timestamp) it means that user hasn't edited anything (yeah, thats obvious). Usually, the insert time stamp is marked as not updateable. So, you have an easy way to audit, ¿why do you need the update field as null? it my helpLonee
I need to return the list of objects that are not updated then I think that can be reached whit that field. Meanwhile, I will remove the annotation and handle the date manually.Reflective
This is actually a nice behaviour, but the worst thing is that it actually does not always set exactly the same value, as a result the tests are flakily failing when comparing these fields: expected: 2021-06-18T12:20:36.492604+02:00[Europe/Berlin] (java.time.ZonedDateTime) but was : 2021-06-18T12:20:36.492092+02:00[Europe/Berlin] (java.time.ZonedDateTime)Goran
P
5

As Andrew S suggested in a comment, a combination of @UpdateTimestamp and @Column(... insertable = false) did the trick form me.

Ptolemy answered 3/1, 2022 at 7:48 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.