Unable to update current time stamp upon database updates

kar :

I have a table where I have a Date field which has a default value of current timestamp. This works fine when I create a row on that table.

When I update that row, I expect that timestamp to automatically be updated but it is not being updated. Appreciate any advice on what I am doing wrong.

This is the field at my Entity class.

// Date is of type import java.util.Date;

@UpdateTimestamp // expecting this to do the auto update. 
@Temporal(TemporalType.TIMESTAMP)
private Date updatedAt; 

This is the query at my Repository interface.

// I don't intend to pass in current timestamp as a 3rd param for updateAt field. I expect it to just auto update to current time stamp.
@Modifying
@Query("update table as t set t.title =?1 where t.Id = ?2")
void update(String title, long id);

The above query updates only title and id but not the updatedAt Date field. Also tried the following under the Entity class which makes no difference.

@PreUpdate
protected void onUpdate(){
    updatedAt = new Date();
}
Hermann Steidel :

I suspected this is normal behavior because @PreUpdate is a JPA/Hibernate feature. When you just use a Query, you are just invoking "plain SQL" not going through Hibernate entity lifecycle. I looked around and found some confirmation:

This was answered here as well: Spring Data JPA @PreUpdate not called when update using @Query from Repository

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=109268&siteId=1
Recommended