Skip to content
Advertisement

Lombok @Builder How create a field with timestamp of value change?

I have the following class:

@Data
@Builder
public class SampleClass<String, String> {
   @NonNull
   String key;

   @NonNull
   String value;
}

Is there any way to add a timestamp for when the class is initialized and when the value is changed/edited/updated?

I have attempted adding:

@Temporal(TemporalType.TIMESTAMP)
private TimeStamp editedAt;

But does not seem to be what I am looking for.

Advertisement

Answer

You could achieve it with a few options. However, Lombok could not help you will it. You have to use other options.

You could use @CreationTimestamp & @UpdateTimestamp:

@Column
@CreationTimestamp
@Temporal(TemporalType.TIMESTAMP)
private Date createAt;

@Column
@UpdateTimestamp
@Temporal(TemporalType.TIMESTAMP)
private Date editedAt;

Another way is to use @PrePersist & @PreUpdate:

@Data
@Builder
public class SampleClass {
   // other fields
   @Column
   @Temporal(TemporalType.TIMESTAMP)
   private Date createdAt;

   @Column
   @Temporal(TemporalType.TIMESTAMP)
   private Date updatedAt;

   @PrePersist
   protected void onCreate() {
     createdAt = new Date();
   }

   @PreUpdate
   protected void onUpdate() {
     updatedAt = new Date();
   }
}
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement