Search code examples
javadatetimejpatimestampplayframework

How to create an auto-generated Date/timestamp field in a 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.

I used to achieve such requirements in the mysql schema.

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


Solution

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