Java 使用 JPA 的上次更新时间戳
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1745890/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Last update timestamp with JPA
提问by nos
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(具体来说是 Eclipselink)。下面的实体有一个时间戳,应该反映该实体上次更新的时间。
What are the strategies for making JPA update that timestamp automatically every time this entity is changed ?
每次更改此实体时,使 JPA 自动更新时间戳的策略是什么?
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;
}
}
采纳答案by ChssPly76
Use @PrePersistand @PreUpdateannotations and write your own event listener.
使用@PrePersist和@PreUpdate注释并编写您自己的事件侦听器。
Take a look at this answerfor details. It's tagged as Hibernate but is applicable to any JPA provider.
有关详细信息,请查看此答案。它被标记为 Hibernate,但适用于任何 JPA 提供程序。
回答by surajz
if you are using mysql, I think you can do the following to disable the timestamps from being updated from entity
如果您使用的是 mysql,我认为您可以执行以下操作来禁止从实体更新时间戳
@Column(name = "lastUpdate", updatable= false, insertable=false)
@Temporal(TemporalType.TIMESTAMP)
private Date lastUpdate;
for oracle you time have to set the timestamps from the entity using @PreUpdate annotation as explained above.
对于oracle,您必须使用@PreUpdate 注释从实体中设置时间戳,如上所述。
回答by Jubz
Actually, surajzanswer works. Consider a scenario where you are tracking 2 timestamps. You want to manually update them via the entity. You'd need to set one to updateble=false
(the one you do not want updated when the record is updated), and leave the other free for updates.
实际上,surajz 的答案是有效的。考虑一个跟踪 2 个时间戳的场景。您想通过实体手动更新它们。您需要将一个设置为updateble=false
(更新记录时您不希望更新的那个),并让另一个免费更新。
That's what worked for me.
这就是对我有用的东西。