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

Creation timestamp and last update timestamp with Hibernate and MySQL(Hibernate 和 MySQL 的创建时间戳和上次更新时间戳)
本文介绍了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 的创建时间戳和上次更新时间戳的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

相关文档推荐

quot;Char cannot be dereferencedquot; error(“Char 不能被取消引用错误)
Java Switch Statement - Is quot;orquot;/quot;andquot; possible?(Java Switch 语句 - 是“或/“和可能的?)
Java Replace Character At Specific Position Of String?(Java替换字符串特定位置的字符?)
What is the type of a ternary expression with int and char operands?(具有 int 和 char 操作数的三元表达式的类型是什么?)
Read a text file and store every single character occurrence(读取文本文件并存储出现的每个字符)
Why do I need to explicitly cast char primitives on byte and short?(为什么我需要在 byte 和 short 上显式转换 char 原语?)