Creation timestamp and last update timestamp with Hibernate and MySQL
For a certain Hibernate entity we have a requirement to store its creation time and the last time it was updated. How would you design this?
What data types would you use in the database (assuming MySQL, possibly in a different timezone that the JVM)? Will the data types be timezone-aware?
What data types would you use in Java ( Date
, Calendar
, long
, ...)?
Whom would you make responsible for setting the timestamps—the database, the ORM framework (Hibernate), or the application programmer?
What annotations would you use for the mapping (eg @Temporal
)?
I'm not only looking for a working solution, but for a safe and well-designed solution.
If you are using the JPA annotations, you can use @PrePersist
and @PreUpdate
event hooks do this:
@Entity
@Table(name = "entities")
public class Entity {
...
private Date created;
private Date updated;
@PrePersist
protected void onCreate() {
created = new Date();
}
@PreUpdate
protected void onUpdate() {
updated = new Date();
}
}
or you can use the @EntityListener
annotation on the class and place the event code in an external class.
Taking the resources in this post along with information taken left and right from different sources, I came with this elegant solution, create the following abstract class
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.MappedSuperclass;
import javax.persistence.PrePersist;
import javax.persistence.PreUpdate;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
@MappedSuperclass
public abstract class AbstractTimestampEntity {
@Temporal(TemporalType.TIMESTAMP)
@Column(name = "created", nullable = false)
private Date created;
@Temporal(TemporalType.TIMESTAMP)
@Column(name = "updated", nullable = false)
private Date updated;
@PrePersist
protected void onCreate() {
updated = created = new Date();
}
@PreUpdate
protected void onUpdate() {
updated = new Date();
}
}
and have all your entities extend it, for instance:
@Entity
@Table(name = "campaign")
public class Campaign extends AbstractTimestampEntity implements Serializable {
...
}
你可以使用@CreationTimestamp
和@UpdateTimestamp
:
@CreationTimestamp
@Temporal(TemporalType.TIMESTAMP)
@Column(name = "create_date")
private Date createDate;
@UpdateTimestamp
@Temporal(TemporalType.TIMESTAMP)
@Column(name = "modify_date")
private Date modifyDate;
链接地址: http://www.djcxy.com/p/44044.html
上一篇: JBoss vs Tomcat再次