问题描述
我有一个带有字段的实体
I have an entity with fields
@Temporal(TemporalType.TIMESTAMP)
@Column(name = "edit_timestamp",
columnDefinition="TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP")
private Date editTimestamp;
@Version
@Column(name = "edit_count")
private short editCount;
private String text;
当我尝试使用 Spring-Data-JPA 进行更新时,我发现 edit_count 有已递增,但 edit_timestamp 仍保持不变.如果我手动调用 SQL
When I try to update with Spring-Data-JPA, I observe edit_count has been incremented, but edit_timestamp still remain the same. If I manually invoke SQL
UPDATE post SET TEXT='456' WHERE post_id=1;
edit_timestamp 已更新.如果我添加
the edit_timestamp is updated. If I add
@PreUpdate
protected void onUpdate() {
editTimestamp = new Date();
}
它没有问题.我的问题是为什么没有 @PreUpdate 没有更新 edit_timestamp?
it works w/o issue. My question is why w/o @PreUpdate the edit_timestamp is not updated?
推荐答案
您需要更改列注释以包含 updatable = false.这将导致 edit_timestamp 列不显示在更新 SQL 中,因此 JPA 提供程序不会包含导致它覆盖默认值的字段的当前值.
You need to change the column annotation to include updatable = false. This will cause the edit_timestamp column to not show up in the update SQL, so the JPA provider won't include the current value of the field which is what is causing it to override the default.
@Temporal(TemporalType.TIMESTAMP)
@Column(name = "edit_timestamp",
updatable = false,
columnDefinition="TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP")
private Date editTimestamp;
这篇关于ON UPDATE CURRENT_TIMESTAMP 和 JPA的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!