JPA Auditing

April 2, 2020

Spring Boot and JPA contain some features that will automatically record audit changes to Entities. I needed to make the following changes to my application to get this to work:

The application needed the @EnableApaAuditing annotation :::java package com.drumcoder.diary;

import org.modelmapper.ModelMapper;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.data.jpa.repository.config.EnableJpaAuditing;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;

@SpringBootApplication
@EnableJpaAuditing(auditorAwareRef = "auditorAware")
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class DiaryApplication {

    @Bean
    public ModelMapper modelMapper() {
        return new ModelMapper();
    }

    public static void main(String[] args) {
        SpringApplication.run(DiaryApplication.class, args);
    }
}

All the entities needed a specific, empty, RevisionRepository:

package com.drumcoder.diary.service.appointment;

import org.springframework.data.repository.history.RevisionRepository;
import org.springframework.stereotype.Repository;

@Repository
public interface AppointmentRevisionRepository extends RevisionRepository<AppointmentEntity, Long, Integer> {

}

Entities needed to be annotated with @Audited, and @AuditOverride to pick up parent class attributes

@Entity
@Audited
@AuditOverride(forClass = AbstractModelEntity.class, isAudited = true)
@Table(name = "appointment", indexes = { @Index(columnList = "appointment_date", unique = false) })
public class AppointmentEntity extends AbstractModelEntity<String> {
// ...
}