Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mysql 5.6 column on update current timestamp not working in hibernate

I have a column called lastModified in the table answer, something like following

 +--------------+----------------+------+-----+-------------------+-----------------------------+
 | Field        | Type           | Null | Key | Default           | Extra                       |
 +--------------+----------------+------+-----+-------------------+-----------------------------+
 | answerId     | int(11)        | NO   | PRI | NULL              | auto_increment              |
 | totalComment | int(11)        | NO   |     | 0                 |                             |
 | totalView    | int(11)        | NO   |     | 0                 |                             |
 | totalSpam    | int(11)        | YES  |     | 0                 |                             |
 | lastModified | timestamp      | NO   |     | CURRENT_TIMESTAMP | on update CURRENT_TIMESTAMP |
 +--------------+----------------+------+-----+-------------------+-----------------------------+

Whenever I manullay update to any one of totalComment, totalView, totalSpam columns in mysql console the lastModifed column also get modified with current timestamp. But when I am doing the same thing with hibernate application it is not getting modified.

My application is implemented as part of spring data jpa. In application.yml I tried using both org.hibernate.dialect.MySQLDialect and org.hibernate.dialect.MySQL5Dialect but no help.

In my annotated Answer entity class lastModified column is declared as following

@Column
private Date lastModified;

public Date getLastModified() {
    return lastModified;
}

public void setLastModified(Date lastModified) {
    this.lastModified = lastModified;
}

Any Idea ?

like image 966
Bhupati Patel Avatar asked Dec 18 '15 06:12

Bhupati Patel


1 Answers

As the @Shadow mentioned, your current schema design implies that you want MySQL to automatically set the lastModified field for you (on update CURRENT_TIMESTAMP). So if you pass null from your Java code, then it should work as expected. Try using the updatable = false option in your column definition to tell JPA not to send a value to MySQL:

@Column(name = "lastModified",
        updatable = false)
private Date lastModified;

My guess as to what is currently happening is that Hibernate is populating the lastModified field with the value from the database, and then your JPA code is then persisting this same value back to MySQL. So it appears that the value is not being updated. But what is really happening is that your JPA code is doing an update with the same old value.

like image 86
Tim Biegeleisen Avatar answered Nov 02 '22 22:11

Tim Biegeleisen