Search code examples
javaspringjpaentityauditing

How to keep @LastModifiedBy field empty (null) when creating a new entity, set only on update


Spring JPA auditable entity contains fields similar to this:

@EntityListeners(AuditingEntityListener.class)
...
{
  @CreationTimestamp
  @Column(name = "created_date", nullable = false)
  @JsonIgnore
  private LocalDateTime createdDate;

  @CreatedBy
  @Column(name = "created_by", nullable = false)
  @JsonIgnore
  private Long createdBy;

  @UpdateTimestamp
  @Column(name = "modified_date")
  @JsonIgnore
  private LocalDateTime lastModifiedDate;

  @LastModifiedBy
  @Column(name = "modified_by")
  @JsonIgnore
  private Long lastModifiedBy;
}

createdBy and lastModifiedBy are IDs of an User that created the entity.

The fields are set by Spring JPA auditing in a similar manner:

  @Bean
  public AuditorAware<Long> auditorProvider() {
    return () -> {
      AppUserPrincipal principal = AuthUtils.getCurrentUser();
      return Optional.of(principal.getUserId());
    };
  }

By default, when a new entity is created, the IDs createdBy and lastModifiedBy have the same values (and dates).

How to set lastModifiedBy and lastModifiedDate only when the entity is updated, not set them with the creator's values initially?


Solution

  • I found a neat solution to remove @UpdateTimestamp and @LastModifiedBy annotations, and use JPA Entity Lifecycle events.

    Example on how I created my @PreUpdate hook to set modifier values:

    @PreUpdate
    public void edit() {
        AppUserPrincipal user = AuthUtils.getCurrentUser();
        this.setLastModifiedDate(LocalDateTime.now());
        this.setLastModifiedBy(user.getUserId());
    }