Hibernate 和 MySQL 的创建时间戳和上次更新时间戳

2022-01-13 00:00:00 timestamp java Hibernate

对于某个 Hibernate 实体,我们需要存储其创建时间和上次更新时间.你会如何设计这个?

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?

  • 您将在数据库中使用哪些数据类型(假设 MySQL,可能与 JVM 在不同的时区)?数据类型是否可以识别时区?

  • 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?

你会在 Java 中使用哪些数据类型(DateCalendarlong、...)?

What data types would you use in Java (Date, Calendar, long, ...)?

您会让谁负责设置时间戳——数据库、ORM 框架(Hibernate)或应用程序程序员?

Whom would you make responsible for setting the timestamps—the database, the ORM framework (Hibernate), or the application programmer?

您会为映射使用哪些注释(例如 @Temporal)?

What annotations would you use for the mapping (e.g. @Temporal)?

我不仅在寻找可行的解决方案,而且还在寻找安全且设计良好的解决方案.

I'm not only looking for a working solution, but for a safe and well-designed solution.

推荐答案

如果你使用的是 JPA 注解,你可以使用 @PrePersist@PreUpdate 事件钩子来做这个:

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();
  }
}

或者您可以在类上使用 @EntityListener 注释并将事件代码放在外部类中.

or you can use the @EntityListener annotation on the class and place the event code in an external class.

相关文章