我有一个表,其中有一个日期字段,该字段的默认值为当前时间戳。当我在该表上创建一行时,这很好用。
当我更新该行时,我希望时间戳会自动更新,但它并没有被更新。感谢对我做错了什么的任何建议。
这是我的实体类中的字段。
// Date is of type import java.util.Date;
@UpdateTimestamp // expecting this to do the auto update.
@Temporal(TemporalType.TIMESTAMP)
private Date updatedAt;
这是在我的 Repository 界面上的查询。
// 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();
}
最佳答案
我怀疑这是正常行为,因为@PreUpdate 是 JPA/Hibernate 的一个特性。当您只使用查询时,您只是在调用“普通 SQL”,而不是通过 Hibernate 实体生命周期。我环顾四周,发现了一些证据:
这里也有回答: Spring Data JPA @PreUpdate not called when update using @Query from Repository
关于java - 无法在数据库更新时更新当前时间戳,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54638282/