How can you make a created_at column generate the creation date-time automatically like an ID automatically gets created?
JPA
There isn't anything as convenient as annotating the Timestamp field directly but you could use the @PrePersist
, @PreUpdate
annotations and with little effort achieve the same results.
Hibernate
@CreationTimestamp
- Documentation@UpdateTimestamp
- Documentation
Spring Data JPA
@CreatedDate
- Documentation@LastModifiedDate
- Documentation
You can create a BaseEntity. Each entity extends the BaseEntity. In the Base entity ,it will set the time automatically
@Data
@MappedSuperclass
@Inheritance(strategy = InheritanceType.TABLE_PER_CLASS)
public abstract class BaseEntity implements Serializable {
@Id
@Column(name = "Id")
private String id;
@Column(name = "deleted", columnDefinition = "Bit(1) default false")
private boolean deleted = false;
@Column(name = "DataChange_CreatedBy", nullable = false)
private String dataChangeCreatedBy;
@Column(name = "DataChange_CreatedTime", nullable = false)
private Date dataChangeCreatedTime;
@Column(name = "DataChange_LastModifiedBy")
private String dataChangeLastModifiedBy;
@Column(name = "DataChange_LastTime")
private Date dataChangeLastModifiedTime;
@PrePersist
protected void prePersist() {
if (this.dataChangeCreatedTime == null) dataChangeCreatedTime = new Date();
if (this.dataChangeLastModifiedTime == null) dataChangeLastModifiedTime = new Date();
}
@PreUpdate
protected void preUpdate() {
this.dataChangeLastModifiedTime = new Date();
}
@PreRemove
protected void preRemove() {
this.dataChangeLastModifiedTime = new Date();
}
}
Extend the following abstract class in your entity:
@MappedSuperclass
@EntityListeners(AuditingEntityListener.class)
public abstract class DateAudit implements Serializable {
@CreatedDate
@Column(name = "created_at", nullable = false, updatable = false)
private Date createdAt;
@LastModifiedDate
@Column(name = "updated_at")
private LocalDateTime updatedAt;
}
Don't forget to enable JPA Auditing feature using @EnableJpaAuditing
Read this: https://docs.spring.io/spring-data/jpa/docs/1.7.0.DATAJPA-580-SNAPSHOT/reference/html/auditing.html