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

标签 java hibernate spring-boot

我有一个表,其中有一个日期字段,该字段的默认值为当前时间戳。当我在该表上创建一行时,这很好用。

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

这是我的实体类中的字段。

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

相关文章:

java - 静态内容未从 Spring Boot 应用程序加载到 JSP 页面中

java - 根据 Spring Boot 中的角色获取用户列表

spring - 替换 AuthorizationRequest 后 HttpSession 为空

java - 如何在 Java 中分割一个整数

java : I am getting only one element while parsing the values

java - 使用 MapReduce 在图中查找距离为 2 的节点对

java - 连接列留空

java - 获取导致 com.microsoft.sqlserver.jdbc.SQLServerException : String or binary data would be truncated 的列的任何方法

java - System.in 属于什么输入类,为什么?

java - Hibernate JPA无法在SQL Server中创建索引