hibernateormjpa

How to autogenerate created or modified timestamp field?


My entity class:

@Entity
@Table(name = "user")
public class User implements Serializable {
    private static final long serialVersionUID = 1L;

    @Id
    @SequenceGenerator(name = "USER_ID_GENERATOR", sequenceName = "USER_SEQ")
    @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "USER_ID_GENERATOR")
    @Column(name = "user_id")
    private long userId;


    @Temporal(TemporalType.DATE)
    private Date created;

    @Temporal(TemporalType.DATE)
    private Date modified;

    //setters and getters...
}

I would like to created and modified fields complement each other automatically when you create or modify the object. created and modified fields should be of type TIMESTAMP.

How do I achieve that?


Solution

  • You can just create a new Date() whenever your instance is created, and then update the updated field whenever the entity gets updated:

    private Date created = new Date();
    private Date updated = new Date();
    
    @PreUpdate
    public void setLastUpdate() {  this.updated = new Date(); }
    

    Don't provide a setter for any of these methods, only getters.