Auditing

Basic Spring
≈ 2 min read

Automatic timestamp fields

Many tables need technical metadata: when a record was created and when it was last changed. Filling these fields manually in every service is inconvenient and easy to forget. Spring Data supports auditing — infrastructure that can set these values when an entity is saved.

@Configuration
@EnableJdbcAuditing
class PersistenceConfig {
}

@Table("customers")
class Customer {
    @Id
    Long id;

    String name;

    @CreatedDate
    Instant createdAt;

    @LastModifiedDate
    Instant updatedAt;
}

@EnableJdbcAuditing enables auditing support for Spring Data JDBC. @CreatedDate marks the creation-time field, and @LastModifiedDate marks the last-modification field. When an entity is saved through Spring Data infrastructure, these values are populated by the corresponding callbacks.

Auditing does not replace business data

The technical modification time of a record and, for example, the time when an order was confirmed are different things. Auditing is a good fit for technical persistence history, while domain events are better modeled with separate fields that change according to business rules.

Auditing can also be extended with user information. Spring Data supports fields for the creator and last modifier as well, but the application must provide a way to determine the current user.