Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ON UPDATE CURRENT_TIMESTAMP and JPA

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?

like image 840
Lee Chee Kiam Avatar asked Jul 06 '11 13:07

Lee Chee Kiam


People also ask

What is on update Current_timestamp in MySQL?

With an ON UPDATE CURRENT_TIMESTAMP clause but no DEFAULT clause, the column is automatically updated to the current timestamp but does not have the current timestamp for its default value. The default in this case is type dependent.

What creates timestamp?

A timestamp is the current time of an event that a computer records. Through mechanisms, such as the Network Time Protocol, a computer maintains accurate current time, calibrated to minute fractions of a second. Such precision makes it possible for networked computers and applications to communicate effectively.

How do I add a timestamp to a column in SQL?

How do I add a TIMESTAMP to a MySQL table? Here is the SQL you can use to add the column in: ALTER TABLE `table1` ADD `lastUpdated` TIMESTAMP ON UPDATE CURRENT_TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ; This adds a column called 'lastUpdated' with a default value of the current date/time.


1 Answers

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;
like image 130
Jeff Putney Avatar answered Sep 22 '22 15:09

Jeff Putney