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

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

问题描述

我想在实体对象上添加一个Date / DateTime / Timestamp字段,当实体创建/持久化并设置为now时,该对象将被自动创建,从不再次更新。

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架构中

在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 your 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中创建自动生成的Date / timestamp字段! / JPA?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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