JPA的上次更新时间戳

我正在玩JPA(Eclipselink是具体的)。 下面的实体有一个时间戳,应该反映上次更新该实体的时间。

每次更改此实体时,JPA更新时间戳的策略是什么?

如果我还想要一个’创建’时间戳,我将如何进行,仅在实体首次持久化时设置,永远不允许再次更改?

@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注释并编写自己的事件监听器。

有关详细信息,请查看此答案 。 它被标记为Hibernate,但适用于任何JPA提供程序。

如果您使用的是mysql,我认为您可以执行以下操作来禁用从实体更新的时间戳

 @Column(name = "lastUpdate", updatable= false, insertable=false) @Temporal(TemporalType.TIMESTAMP) private Date lastUpdate; 

对于oracle,您需要使用@PreUpdate注释从实体设置时间戳,如上所述。

实际上, surajz回答有效。 考虑一个跟踪2个时间戳的场景。 您想通过实体手动更新它们。 您需要将一个设置为updateble=false (更新记录时不希望更新的那个),并让另一个免费更新。

这对我有用。