【发布时间】:2020-03-03 22:12:32
【问题描述】:
在 MySQL 数据库中,每个表都有一个列 updated,它被创建为
[...] `updated` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
正如预期的那样,每次行更新都会触发时间戳对 CURRENT_TIMESTAMP 的更新。当我通过 SQL shell、命令行、DBeaver、Workbench BUT
更新一行时,这是真的使用 Hibernate(Spring Boot 2,Spring Data JPA)不起作用。我的意思是,伪代码如:
[Tx]
entity = repository.findById(1) --> Returns my entity with updated == 1L
entity.setProperty("other value")
repository.save(entity)
[/Tx]
此时,DB 条目已更新(“其他值”为当前值)但updated 列仍为 1L,其中应为 CURRENT_TIMESTAMP
我以前也绕过这个问题
- 将属性注释为
@UpdateTimestamp或h - 使用@PrePersist && @PreUpdate 注释一个方法,这将以编程方式在
UPDATESQL 语句之前设置当前时间戳
这两种方法的问题在于,在我的 Tx 用完之前,我没有更新的值:
[Tx]
entity.getUpdated() == 1L
entity.setName("other")
repository.save(entity) // at this point the updated is still == 1L
repository.findById() // at this point the updated is still == 1L
[/Tx]
[Tx]
repository.findById() // good timestamp value
[Tx]
MySQL一开始不触发更新正常吗?
有没有办法在同一个事务中获取更新的值?
【问题讨论】:
-
您能否运行
SHOW CREATE TABLE yourTable并检查此时间戳列是否实际上具有ON UPDATE子句?我怀疑它可能不会。 -
是的,确实如此。如问题中所述,当使用命令行或 DBeaver 等 SQL IDE 时,会发生更新。只有在通过 JPA 时这不起作用(可能是其他框架,但我不能确定)