Home > Back-end >  JPA entity update via "getById & save" didn't updated it's updatedtimestamp colu
JPA entity update via "getById & save" didn't updated it's updatedtimestamp colu

Time:09-17

I'm now trying to update the Entity's column by using "getById & save", like below.

// update "title" column 
val entityRef = entityRepository.getById(entityID)
entityRef.title = futureTitle 
return entityRepository.save(entityRef)

However, if I running the code, the updatedtimestamp column(which is described as CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP) not changed even though the column has been perfectly updated.

It seems like the updatedtimestamp column only updates when I use the custom "UPDATE" query.

    @Modifying
    @Transactional
    @Query("update Entity p set p.title = :newTitle where p.id = :entityId")
    fun updateEntityTitle(entityId: Long, newTitle: String)

Could I know why updating entity by "getById & save" didn't made a change to the updatedtimestamp?

Thanks in advance!

CodePudding user response:

ON UPDATE CURRENT_TIMESTAMP is a construct of MySql's SQL dialect. It is described as follows in the documentation:

An auto-updated column is automatically updated to the current timestamp when the value of any other column in the row is changed from its current value. An auto-updated column remains unchanged if all other columns are set to their current values. To prevent an auto-updated column from updating when other columns change, explicitly set it to its current value. To update an auto-updated column even when other columns do not change, explicitly set it to the value it should have (for example, set it to CURRENT_TIMESTAMP).

Since all JPA implementation update all columns no matter, if they changed or not they will also provide a value for your CURRENT_TIMESTAMP column thus preventing any automatic update as described in the documentation.

You have various ways to get an update timestamp with this technology stack:

  1. You can use dynamic inserts to only update fields that changed. Note that in most cases this is bad for performance. See Hibernate: Dirty Checking and Only Update of Dirty Attributes?

  2. You can make the column read only by using @Column(updatable=false). See JPA readonly mapping

  3. Instead of using the MySql feature you may use the Hibernates UpdateTimestamp for this purpose

  4. Or you use JPAs EntityListener.

  5. And since you seem to use Spring Data JPA you may also use Spring Datas @LastModifiedDate.

  • Related