This article is participating in “Java Theme Month – Java Debug Notes Event”, see < Event link > for more details.
Question: Use Hibernate and MySQL to create and last update timestamps
For some Hibernate entities, we need to store when they were created and when they were last updated. How would you design it?
1, which data types will you use in the database (assuming MySQL, possibly different from JVM time zones)? Is the data type time zone sensitive?
2, which data types will you use in Java (date, calendar, long,…) ?
3. Who will be responsible for setting the timestamp (database, ORM framework (Hibernate) or application programmer)?
4. Which annotations will you use for mapping (e.g. @temporal)?
I’m not only looking for a solution that works, but also one that is safe and well designed.
Answer 1:
If you are using JPA annotations, you can do this using @prepersist and @preUpdate event hooks:
@Entity
@Table(name = "entities")
public class Entity {...private Date created;
private Date updated;
@PrePersist
protected void onCreate(a) {
created = new Date();
}
@PreUpdate
protected void onUpdate(a) {
updated = newDate(); }}Copy the code
Alternatively, you can annotate the class with @EntityListener and place the event code in the external class.
Answer 2:
You can use @creationtimestamp and @updatetimestamp:
@CreationTimestamp
@Temporal(TemporalType.TIMESTAMP)
@Column(name = "create_date")
private Date createDate;
@UpdateTimestamp
@Temporal(TemporalType.TIMESTAMP)
@Column(name = "modify_date")
private Date modifyDate;
Copy the code
Answer 3:
Using the resources in this article and the information I’ve obtained from various sources, I’ve brought this elegant solution and created the following abstract classes
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(a) {
updated = created = new Date();
}
@PreUpdate
protected void onUpdate(a) {
updated = newDate(); }}Copy the code
Your subclass inherits the abstract class:
@Entity
@Table(name = "campaign")
public class Campaign extends AbstractTimestampEntity implements Serializable {... }Copy the code