使用 Hibernate 和 MySQL 创建时间戳和上次更新时间戳 [英] Creation timestamp and last update timestamp with Hibernate and MySQL

查看:35
本文介绍了使用 Hibernate 和 MySQL 创建时间戳和上次更新时间戳的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于某个 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.

这篇关于使用 Hibernate 和 MySQL 创建时间戳和上次更新时间戳的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆