无法在数据库更新时更新当前时间戳

我有一个表,其中有一个 Date 字段,该字段具有当前时间戳的默认值。当我在该表上创建一行时,这工作正常。


当我更新该行时,我希望该时间戳能够自动更新,但它没有被更新。感谢任何关于我做错了什么的建议。


这是我的实体类的字段。


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


@UpdateTimestamp // expecting this to do the auto update. 

@Temporal(TemporalType.TIMESTAMP)

private Date updatedAt; 

这是我的存储库界面上的查询。


// 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);

上面的查询只更新 title 和 id 而不是 updatedAt Date 字段。还在 Entity 类下尝试了以下内容,这没有区别。


@PreUpdate

protected void onUpdate(){

    updatedAt = new Date();

}


德玛西亚99
浏览 212回答 1
1回答

慕尼黑8549860

我怀疑这是正常行为,因为 @PreUpdate 是 JPA/Hibernate 功能。当您只使用查询时,您只是在调用“普通 SQL”,而不是通过 Hibernate 实体生命周期。我环顾四周,发现了一些确认:这也在这里得到了回答: Spring Data JPA @PreUpdate not called when update using @Query from Repository
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java