Java, JPA, Spring, Spring Data

Create and modification date with Spring Data

Using created and last modified fields for an entity is considered general pattern and a good practice. It provides you the information about what and when happens in your database, therefore makes your life easier when the time of problem solving comes.

As we love to automatize such boring tasks, using Hibernate it is common to use  @PrePersist and @PreUpdate annotations, defined in a kind of “JpaBaseEntity” mother of all entities in the project. In this case you define the corresponding methods like this:

@PrePersist
public void prePersist() {
    this.setCreated(ZonedDateTime.now());
    this.setModified(ZonedDateTime.now());
}

 

It is not too bad, but using Spring Data makes your life even easier. It has the possibility to automatic fill up such fields using annotations.

@CreatedDate: Declares a field as the one representing the date the entity containing the field was created.

@LastModifiedDate: Declares a field as the one representing the date the entity containing the field was recently modified.

You need only to mark a field with the corresponding annotation and let Spring do the magic. The field must have a type, that implements the TemporalAccessor interface. Also, all usual Date and Time types in the java.time package will do.

Obviously you still can use a base entity class, but in case of only this dates are common in your entities, you can spare the class hierarchy using the annotations.

You can also define audition features, using the @CreatedBy and @LastModifiedBy annotations from the same package.

Advertisement