ON UPDATE CURRENT_TIMESTAMP and JPA

Viewed 14917

I have an entity with fields

@Temporal(TemporalType.TIMESTAMP)
@Column(name = "edit_timestamp", 
        columnDefinition="TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP")
private Date editTimestamp;

@Version
@Column(name = "edit_count")
private short editCount;

private String text;

When I try to update with Spring-Data-JPA, I observe edit_count has been incremented, but edit_timestamp still remain the same. If I manually invoke SQL

UPDATE post SET TEXT='456' WHERE post_id=1;

the edit_timestamp is updated. If I add

@PreUpdate
protected void onUpdate() {
    editTimestamp = new Date();
}

it works w/o issue. My question is why w/o @PreUpdate the edit_timestamp is not updated?

3 Answers

You can mark the variables as update or creation timestamps in your entity. In the following example you can see how this can be done very easily using hibernate annotations:

@UpdateTimestamp
private LocalDateTime editTimestamp;

@CreationTimestamp
private LocalDateTime creationTimestamp;

Just for the reference and to make sure there is no confusion, I am using the following package imports for the respective datatypes and annotations:

import org.hibernate.annotations.CreationTimestamp
import org.hibernate.annotations.UpdateTimestamp
import java.time.LocalDateTime
Related