如何在 Play 中创建自动生成的日期/时间戳字段!/JPA? [英] How to create an auto-generated Date/timestamp field in a Play! / JPA?

查看:15
本文介绍了如何在 Play 中创建自动生成的日期/时间戳字段!/JPA?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在实体对象上添加一个日期/日期时间/时间戳字段,该字段将在实体创建/持久化并设置为现在"时自动创建,不再更新.

I'd like to add a Date/DateTime/Timestamp field on an entity object, that will be automatically created when the entity is created/persisted and set to "now", never to be updated again.

其他用例包括始终更新以包含实体的最后修改日期的字段.

Other use cases included fields that were always updated to contain the last modification date of the entity.

我曾经实现过这样的要求 在mysql架构中.

I used to achieve such requirements in the mysql schema.

在 Play 中执行此操作的最佳方法是什么!/JPA?

What's the best way to do this in Play! / JPA?

推荐答案

有一个代码片段,您可以对其进行调整以实现您想要的.看一看:

There is a code snippet that you can adapt to achieve what you want. Take a look:

// Timestampable.java

package models;

import java.util.Date;

import javax.persistence.Column;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.MappedSuperclass;
import javax.persistence.PrePersist;
import javax.persistence.PreUpdate;
import javax.persistence.Version;

import play.db.ebean.Model;

@MappedSuperclass
public class Timestampable extends Model {

  @Id
  @GeneratedValue
  public Long id;

  @Column(name = "created_at")
  public Date createdAt;

  @Column(name = "updated_at")
  public Date updatedAt;

  @Version
  public int version;

  @Override
  public void save() {
    createdAt();
    super.save();
  }

  @Override
  public void update() {
    updatedAt();
    super.update();
  }

  @PrePersist
  void createdAt() {
    this.createdAt = this.updatedAt = new Date();
  }

  @PreUpdate
  void updatedAt() {
    this.updatedAt = new Date();
  }
}

这篇关于如何在 Play 中创建自动生成的日期/时间戳字段!/JPA?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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