Auditing

Basic Spring
≈ 1 min read

Technical fields without manual population

Entities often have technical fields such as the record creation time and the time of the last modification. If every service assigns them manually, code is duplicated and it is easy to forget to update one of the values. Spring Data JPA can populate such fields through auditing.

@Configuration
@EnableJpaAuditing
class PersistenceConfig {
}

@Entity
@EntityListeners(AuditingEntityListener.class)
class Customer {
    @Id
    @GeneratedValue
    Long id;

    @CreatedDate
    Instant createdAt;

    @LastModifiedDate
    Instant updatedAt;
}

@EnableJpaAuditing enables the auditing infrastructure, and AuditingEntityListener connects it to the entity lifecycle. @CreatedDate marks the creation-time value, while @LastModifiedDate marks the last-modification time.

Auditing stores technical history

These fields are useful for questions such as “when did this record appear in storage?” and “when was it changed last?”. But they do not replace domain dates: for example, paidAt or approvedAt should change according to business rules, not simply on every entity update.

Auditing can store the author of a change as well. For @CreatedBy and @LastModifiedBy, the application additionally needs a way to tell Spring Data who the current user is.