How to create an auto-generated Date/timestamp field in a Play! / JPA?

后端 未结 3 2231
说谎
说谎 2020-12-14 18:56

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

3条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-14 19:04

    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();
      }
    }
    

提交回复
热议问题