Mastering Auditing in Spring Data JPA: Step‑by‑Step Guide

This tutorial explains why auditing is essential, outlines the benefits such as data tracking, security, troubleshooting and compliance, and provides a complete Spring Data JPA implementation with code examples, testing procedures, and required dependencies.

Spring Full-Stack Practical Cases
Spring Full-Stack Practical Cases
Spring Full-Stack Practical Cases
Mastering Auditing in Spring Data JPA: Step‑by‑Step Guide

Environment: SpringBoot 2.7.16

1. Why enable auditing?

Data change tracking: Auditing records creation, modification, deletion timestamps and operators, useful for history and rollback.

Security assurance: Tracks who performed which actions, helping detect misuse and providing evidence for investigations.

Problem diagnosis and recovery: Audit logs help pinpoint operations before a failure, speeding up troubleshooting.

Compliance and regulatory requirements: Provides required logs and reports to satisfy industry standards.

Spring Data JPA supports auditing through annotations such as @CreatedDate, @LastModifiedDate, @CreatedBy, @LastModifiedBy.

2. Implementation steps

Add @EntityListeners(AuditingEntityListener.class) to entity classes.

Enable auditing in the application entry class with @EnableJpaAuditing.

Annotate fields with @CreatedDate, @LastModifiedDate, @CreatedBy, @LastModifiedBy. Implement AuditorAware to supply the current user.

Example entity:

@Entity
@Table(name="t_account")
public class Account {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String name;
    private BigDecimal amount;
    private Integer version;
    @CreatedBy
    private String createUser;
    @Temporal(TemporalType.TIMESTAMP)
    @CreatedDate
    private Date createTime;
    @LastModifiedBy
    private String lastUpdateUser;
    @Temporal(TemporalType.TIMESTAMP)
    @LastModifiedDate
    private Date lastUpdateTime;
}

AuditorAware implementation:

public class OperatorAuditingAware implements AuditorAware<String> {
    @Override
    public Optional<String> getCurrentAuditor() {
        // Retrieve current user from Spring Security or return a default
        return Optional.of("pack");
    }
}

Enable listener on an entity:

@EntityListeners({AuditingEntityListener.class})
public class Customer {}

Enable auditing in the main class:

@EnableJpaAuditing
public class ZzzzSbApplication {}

Test adding a record:

@Resource
private CustomerRepository cr;

@Test
public void testSave() {
    Customer customer = new Customer();
    customer.setAmount(new BigDecimal("6666"));
    customer.setName("张三");
    customer.setVersion(1);
    cr.save(customer);
}

Result shows all four audit fields automatically populated.

Test updating a record:

@Test
public void testUpdate() {
    Customer customer = cr.findById(1L).orElseGet(() -> new Customer());
    customer.setId(1L);
    customer.setAmount(new BigDecimal("8888"));
    cr.save(customer);
}

Result shows updated auditor and timestamp.

Note: Auditing requires spring-aspects.jar on the classpath.

By using @EnableJpaAuditing together with @CreatedDate, @LastModifiedDate, @CreatedBy, and @LastModifiedBy, developers can easily implement comprehensive auditing in Spring Data JPA.

Done.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

javabackend-developmentAuditingjpaspring-data-jpa
Spring Full-Stack Practical Cases
Written by

Spring Full-Stack Practical Cases

Full-stack Java development with Vue 2/3 front-end suite; hands-on examples and source code analysis for Spring, Spring Boot 2/3, and Spring Cloud.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.