Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
631 views
Welcome To Ask or Share your Answers For Others

1 Answer

You need to change the column annotation to include updatable = false. This will cause the edit_timestamp column to not show up in the update SQL, so the JPA provider won't include the current value of the field which is what is causing it to override the default.

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...