问题描述
对于某个 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 中使用哪些数据类型(Date、Calendar、long、...)?
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 的创建时间戳和上次更新时间戳的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!


大气响应式网络建站服务公司织梦模板
高端大气html5设计公司网站源码
织梦dede网页模板下载素材销售下载站平台(带会员中心带筛选)
财税代理公司注册代理记账网站织梦模板(带手机端)
成人高考自考在职研究生教育机构网站源码(带手机端)
高端HTML5响应式企业集团通用类网站织梦模板(自适应手机端)