JPA的上次更新时间戳 [英] Last update timestamp with JPA
问题描述
我正在玩JPA(Eclipselink具体)。下面的实体有一个
时间戳,它应该反映每次该实体最后一次更新。
I'm playing around a bit with JPA(Eclipselink to be specific). The below entity have a timestamp that's supposed to reflect whenever that entity was last updated.
每次$每次自动生成时间戳的JPA更新策略是什么b $ b这个实体被改变了吗?
What are the strategies for making JPA update that timestamp automatically every time this entity is changed ?
如果我还想要一个'创建'时间戳,我将如何进行,只有在实体第一次持久化时设置,永远不允许是否会再次更改?
How would I go about if I also want a 'creation' timestamp, only set when the entity is first persisted, never allowed to be changed again ?
@Entity
public class Item implements Serializable {
private static final long serialVersionUID = 1L;
private Integer id;
private String note;
public Item () {
}
@Id
@GeneratedValue(strategy=SEQUENCE)
@Column(unique=true, nullable=false)
public Integer getId() {
return this.id;
}
public void setId(Integer id) {
this.id = id;
}
@Column(length=255)
@Column(nullable=false)
public String getNote() {
return this.note;
}
public void setNote(String note) {
this.note = note;
}
@Column(nullable=false)
public Timestamp getUpdated() {
return this.updated;
}
public void setUpdated(Timestamp updated) {
this.updated = updated;
}
}
推荐答案
使用 @PrePersist 和 @PreUpdate 注释并撰写你自己的事件监听器。
Use @PrePersist and @PreUpdate annotations and write your own event listener.
看看这个答案了解详情。它被标记为Hibernate,但适用于任何JPA提供商。
Take a look at this answer for details. It's tagged as Hibernate but is applicable to any JPA provider.
这篇关于JPA的上次更新时间戳的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!