Learnitweb

How would you audit entity creation and update times automatically?

In Spring Boot with JPA/Hibernate, you can automatically track entity creation and update timestamps by using JPA auditing. This allows you to maintain fields like createdAt and updatedAt without manually setting them in every service method. Here’s a detailed guide:

1. Enable JPA Auditing

In your Spring Boot application, enable auditing by adding @EnableJpaAuditing to a configuration or main class:

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.data.jpa.repository.config.EnableJpaAuditing;

@SpringBootApplication
@EnableJpaAuditing
public class MyApplication {
    public static void main(String[] args) {
        SpringApplication.run(MyApplication.class, args);
    }
}

2. Create Base Entity for Auditing Fields

You can create a base class that all entities inherit:

import jakarta.persistence.*;
import org.springframework.data.annotation.CreatedDate;
import org.springframework.data.annotation.LastModifiedDate;
import org.springframework.data.jpa.domain.support.AuditingEntityListener;

import java.time.LocalDateTime;

@MappedSuperclass
@EntityListeners(AuditingEntityListener.class)
public abstract class Auditable {

    @CreatedDate
    @Column(name = "created_at", nullable = false, updatable = false)
    private LocalDateTime createdAt;

    @LastModifiedDate
    @Column(name = "updated_at")
    private LocalDateTime updatedAt;

    // Getters
    public LocalDateTime getCreatedAt() { return createdAt; }
    public LocalDateTime getUpdatedAt() { return updatedAt; }
}

Explanation:

  • @CreatedDate → Set automatically when entity is first persisted.
  • @LastModifiedDate → Updated automatically whenever the entity is updated.
  • @EntityListeners(AuditingEntityListener.class) → Hooks into entity lifecycle.
  • @MappedSuperclass → Allows inheritance of fields without creating a separate table.

3. Extend Base Entity

import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;

@Entity
public class Product extends Auditable {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    private String name;
    private double price;

    // Getters and setters
}
  • Now Product automatically has createdAt and updatedAt fields populated by JPA auditing.

4. Optional: Track CreatedBy / ModifiedBy

You can also automatically track who created or updated the entity:

import org.springframework.data.annotation.CreatedBy;
import org.springframework.data.annotation.LastModifiedBy;

@CreatedBy
private String createdBy;

@LastModifiedBy
private String modifiedBy;
  • You need to provide a AuditorAware bean to supply the current user:
import org.springframework.context.annotation.Bean;
import org.springframework.data.domain.AuditorAware;
import org.springframework.stereotype.Component;

import java.util.Optional;

@Component
public class AuditorAwareImpl implements AuditorAware<String> {

    @Override
    public Optional<String> getCurrentAuditor() {
        // Fetch current username from SecurityContext or return a default
        return Optional.of("system");
    }
}

5. Database Column Setup

Example table after auditing:

idnamepricecreated_atupdated_at
1Laptop12002025-09-26 19:302025-09-26 19:35
  • created_at is set only once.
  • updated_at changes on every update.

6. Advantages

  1. Automatic timestamps → No manual handling in service layer.
  2. Works for all entities inheriting the base class.
  3. Integrates with Spring Security to track user actions.
  4. Reduces boilerplate code and improves consistency.

7. Example Usage

Product p = new Product();
p.setName("Mouse");
p.setPrice(25);
productRepository.save(p);

// createdAt and updatedAt set automatically
  • On update:
p.setPrice(30);
productRepository.save(p); // updatedAt changes automatically