Auditing: created and updated timestamps
45 min · Intermediate
Need help? Ask a tutor on WhatsApp (opens in a new tab)Every ShopLite customer needs a created time, and writing setCreatedAt(...) in each service is easy to forget. One missed call sends NULL, and MySQL refuses the row.
Spring Data auditing: @CreatedDate and @LastModifiedDate
Auditing means recording when (and later by whom) a row was created and last changed. JPA lets a listener fill these fields just before each INSERT and UPDATE, so no service code has to.
Three pieces switch on Spring Data auditing: @EnableJpaAuditing, @EntityListeners(AuditingEntityListener.class) and the field annotations. Example 1 wires them for Customer.
Example 1 · AuditingConfig.java and Customer.java with @CreatedDate
Runs in: the mapping-lab practice project (Spring Boot 4.1, Hibernate 7, the ShopLite MySQL database)
// src/main/java/com/shoplite/common/AuditingConfig.javapackage com.shoplite.common;
import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;import org.springframework.data.auditing.DateTimeProvider;import org.springframework.data.jpa.repository.config.EnableJpaAuditing;
import java.time.Clock;import java.time.LocalDateTime;import java.time.ZoneId;import java.time.temporal.ChronoUnit;import java.util.Optional;
@Configuration@EnableJpaAuditing(dateTimeProviderRef = "auditingDateTimeProvider")public class AuditingConfig {
@Bean Clock clock() { return Clock.system(ZoneId.of("Asia/Kolkata")); // ShopLite stores India time }
@Bean DateTimeProvider auditingDateTimeProvider(Clock clock) { // DATETIME columns keep whole seconds, so drop the fraction here return () -> Optional.of(LocalDateTime.now(clock).truncatedTo(ChronoUnit.SECONDS)); }}
package com.shoplite.customer;
import jakarta.persistence.Column;import jakarta.persistence.Entity;import jakarta.persistence.EntityListeners;import jakarta.persistence.GeneratedValue;import jakarta.persistence.GenerationType;import jakarta.persistence.Id;import jakarta.persistence.Table;import org.springframework.data.annotation.CreatedDate;import org.springframework.data.jpa.domain.support.AuditingEntityListener;
import java.time.LocalDateTime;
@Entity@Table(name = "customers")@EntityListeners(AuditingEntityListener.class)public class Customer {
@Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "customer_id") private Integer id;
@Column(name = "full_name", nullable = false, length = 100) private String fullName;
@Column(nullable = false, length = 255, unique = true) private String email;
@Column(length = 15) private String phone;
@CreatedDate @Column(name = "created_at", nullable = false, updatable = false) private LocalDateTime createdAt;
protected Customer() { }
public Customer(String fullName, String email, String phone) { this.fullName = fullName; this.email = email; this.phone = phone; }
public Integer getId() { return id; } public String getFullName() { return fullName; } public String getEmail() { return email; } public String getPhone() { return phone; } public LocalDateTime getCreatedAt() { return createdAt; }
@Override public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof Customer other)) return false; return id != null && id.equals(other.getId()); }
@Override public int hashCode() { return Customer.class.hashCode(); }
@Override public String toString() { return "Customer[id=" + id + ", email=" + email + "]"; }}
Customer sneha = new Customer("Sneha Patil", "sneha.patil@example.com", "9876543209");System.out.println("Before save: " + sneha.getCreatedAt());customers.save(sneha);System.out.println("After save: " + sneha.getCreatedAt());
Customer reloaded = customers.findById(sneha.getId()).orElseThrow();System.out.println("In MySQL: " + reloaded.getCreatedAt());Before save: null DEBUG ... org.hibernate.SQL : insert into customers (created_at,email,full_name,phone) values (?,?,?,?) After save: 2026-10-16T12:34:08 DEBUG ... org.hibernate.SQL : select c1_0.customer_id,c1_0.created_at,c1_0.email,c1_0.full_name,c1_0.phone from customers c1_0 where c1_0.customer_id=? In MySQL: 2026-10-16T12:34:08 The same run without @EnableJpaAuditing: WARN ... org.hibernate.orm.jdbc.error : Column 'created_at' cannot be null org.springframework.dao.DataIntegrityViolationException: could not execute statement [Column 'created_at' cannot be null] [insert into customers (created_at,email,full_name,phone) values (?,?,?,?)]
What this code does
- The
INSERTnow includescreated_at:AuditingEntityListenerset it just before the save, so the object and the row hold the same value at once. - The value is India time in whole seconds, from the
DateTimeProviderbean. Equals methods andtoStringare covered in the next lesson. - Without
@EnableJpaAuditingthe listener does nothing, the field staysnulland MySQL rejects it. The column'sDEFAULTdoes not help, because theINSERTsendsNULLexplicitly.
@CreatedDate fills a field before the first INSERT, and @LastModifiedDate before every INSERT and UPDATE. The value is set in Java before the INSERT, so the saved object holds it at once (Example 1); with insertable = false and MySQL's DEFAULT CURRENT_TIMESTAMP, the object kept null until you loaded it again.
ShopLite's Customer.createdAt uses @CreatedDate with updatable = false, so no later UPDATE can change when a customer registered. Forget @EnableJpaAuditing and nothing fills the field: the INSERT sends NULL and MySQL answers Column 'created_at' cannot be null.
Order of execution
What happens on save()
Put the steps in the order they happen.
DateTimeProvider bean uses a Clock for Asia/Kolkata and cuts off fractions of a second, because DATETIME columns keep whole seconds and hold India time (the fourth section explains why).Hibernate's @CreationTimestamp and @UpdateTimestamp
@CreationTimestamp and @UpdateTimestamp do the same job without Spring Data. Example 2 puts both on a lab Coupon.
Example 2 · @CreationTimestamp and @UpdateTimestamp on a lab Coupon
Runs in: the mapping-lab practice project with a throwaway lab database (ddl-auto=create)
// src/main/java/com/shoplite/lab/Coupon.javapackage com.shoplite.lab;
import jakarta.persistence.Column;import jakarta.persistence.Entity;import jakarta.persistence.GeneratedValue;import jakarta.persistence.GenerationType;import jakarta.persistence.Id;import jakarta.persistence.Table;import org.hibernate.annotations.CreationTimestamp;import org.hibernate.annotations.UpdateTimestamp;
import java.time.LocalDateTime;
@Entity@Table(name = "coupons")public class Coupon {
@Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Integer id;
@Column(nullable = false, length = 20, unique = true) private String code;
@Column(name = "percent_off", nullable = false) private int percentOff;
@CreationTimestamp @Column(name = "created_at", nullable = false, updatable = false) private LocalDateTime createdAt;
@UpdateTimestamp @Column(name = "updated_at", nullable = false) private LocalDateTime updatedAt;
protected Coupon() { }
public Coupon(String code, int percentOff) { this.code = code; this.percentOff = percentOff; }
public Integer getId() { return id; } public LocalDateTime getCreatedAt() { return createdAt; } public LocalDateTime getUpdatedAt() { return updatedAt; }
public void changePercentOff(int percentOff) { this.percentOff = percentOff; }}
// src/main/java/com/shoplite/lab/CouponDemoRunner.javapackage com.shoplite.lab;
import org.springframework.boot.CommandLineRunner;import org.springframework.stereotype.Component;
@Componentclass CouponDemoRunner implements CommandLineRunner {
private final CouponRepository coupons;
CouponDemoRunner(CouponRepository coupons) { this.coupons = coupons; }
@Override public void run(String... args) throws InterruptedException { Coupon fest = coupons.save(new Coupon("FEST20", 20)); System.out.println("Created: " + fest.getCreatedAt() + " | updated: " + fest.getUpdatedAt());
Thread.sleep(2000); // so the update time is visibly later fest.changePercentOff(25); Coupon changed = coupons.save(fest); System.out.println("Created: " + changed.getCreatedAt() + " | updated: " + changed.getUpdatedAt()); }}DEBUG ... org.hibernate.SQL : insert into coupons (code,created_at,percent_off,updated_at) values (?,?,?,?) Created: 2026-10-16T11:34:54.871412 | updated: 2026-10-16T11:34:54.873432 DEBUG ... org.hibernate.SQL : select c1_0.id,c1_0.code,c1_0.created_at,c1_0.percent_off,c1_0.updated_at from coupons c1_0 where c1_0.id=? DEBUG ... org.hibernate.SQL : update coupons set code=?,percent_off=?,updated_at=? where id=? Created: 2026-10-16T11:34:54.871412 | updated: 2026-10-16T11:34:57.198654
What this code does
- Hibernate filled both fields on
INSERTand onlyupdated_atonUPDATE;created_atis alsoupdatable = false, so it is not even in theUPDATE. - The two values on insert differ by about 2 milliseconds: each annotation asks the clock separately, and the JVM's local zone decides the wall-clock time.
- The
saveof a changed object ran aSELECTand then theUPDATE. The Persistence Context module explains why and how to avoid the extrasave.
The two annotations come from org.hibernate.annotations: Hibernate itself sets the field to "now" on INSERT, and on every INSERT and UPDATE respectively, with no listener and no @Enable... annotation. The differences that matter: the Hibernate annotations take the time from the JVM's clock and zone, and they work only for timestamps. Spring Data auditing lets you plug in your own time source (easy to fix in tests) and also offers @CreatedBy and @LastModifiedBy for the user.
ShopLite chooses Spring Data auditing: one mechanism for "when" now and "who" after Spring Security, and a time that does not depend on the server's zone. Small apps with only timestamps are fine with the Hibernate pair.
A @MappedSuperclass for shared audit fields
@MappedSuperclass marks a parent class whose mapped fields are copied into the table of every entity that extends it. The parent has no table of its own and is not an entity, so it cannot be queried.
An AuditableEntity with createdAt, updatedAt and the listener annotation lets each entity say only extends AuditableEntity. Example 3 uses it on a lab coupons table.
Example 3 · AuditableEntity: one @MappedSuperclass for every audited table
Runs in: the mapping-lab practice project with a throwaway lab database (ddl-auto=create)
// src/main/java/com/shoplite/common/AuditableEntity.javapackage com.shoplite.common;
import jakarta.persistence.Column;import jakarta.persistence.EntityListeners;import jakarta.persistence.MappedSuperclass;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 // no table of its own: its fields go into each child's table@EntityListeners(AuditingEntityListener.class)public abstract class AuditableEntity {
@CreatedDate @Column(name = "created_at", nullable = false, updatable = false) private LocalDateTime createdAt;
@LastModifiedDate @Column(name = "updated_at", nullable = false) private LocalDateTime updatedAt;
public LocalDateTime getCreatedAt() { return createdAt; } public LocalDateTime getUpdatedAt() { return updatedAt; }}
// src/main/java/com/shoplite/lab/Coupon.javapackage com.shoplite.lab;
import com.shoplite.common.AuditableEntity;import jakarta.persistence.Column;import jakarta.persistence.Entity;import jakarta.persistence.GeneratedValue;import jakarta.persistence.GenerationType;import jakarta.persistence.Id;import jakarta.persistence.Table;
@Entity@Table(name = "coupons")public class Coupon extends AuditableEntity {
@Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Integer id;
@Column(nullable = false, length = 20, unique = true) private String code;
@Column(name = "percent_off", nullable = false) private int percentOff;
protected Coupon() { }
public Coupon(String code, int percentOff) { this.code = code; this.percentOff = percentOff; }
public Integer getId() { return id; } public String getCode() { return code; } public int getPercentOff() { return percentOff; }
public void changePercentOff(int percentOff) { this.percentOff = percentOff; }}
Coupon fest = coupons.save(new Coupon("FEST20", 20));System.out.println("Created: " + fest.getCreatedAt() + " | updated: " + fest.getUpdatedAt());
Thread.sleep(2000);fest.changePercentOff(25);Coupon changed = coupons.save(fest);System.out.println("Created: " + changed.getCreatedAt() + " | updated: " + changed.getUpdatedAt());DEBUG ... org.hibernate.SQL : create table coupons (id integer not null auto_increment, percent_off integer not null, created_at datetime(6) not null, updated_at datetime(6) not null, code varchar(20) not null, primary key (id)) engine=InnoDB DEBUG ... org.hibernate.SQL : insert into coupons (code,created_at,percent_off,updated_at) values (?,?,?,?) Created: 2026-10-16T11:35:17 | updated: 2026-10-16T11:35:17 DEBUG ... org.hibernate.SQL : select c1_0.id,c1_0.code,c1_0.created_at,c1_0.percent_off,c1_0.updated_at from coupons c1_0 where c1_0.id=? DEBUG ... org.hibernate.SQL : update coupons set code=?,percent_off=?,updated_at=? where id=? Created: 2026-10-16T11:35:17 | updated: 2026-10-16T11:35:20
What this code does
- The
CREATE TABLEshows the inheritedcreated_atandupdated_atcolumns insidecoupons; there is noauditable_entitytable. Couponhas no audit code at all. Spring Data set both fields on insert with one value, and onlyupdatedAton the change, three seconds later.- The runner uses the same
AuditingConfigas Example 1, so values are whole seconds in India time.
A mapped superclass removes repetition when many tables share columns, and it cannot have a repository. Use it only for columns the tables really share.
In ShopLite only customers has created_at, and no table has updated_at, so Customer declares its one field itself. Adding audit columns to ShopLite would be a Flyway migration, later in this section.
Database defaults vs app timestamps, and time zones
A DateTimeProvider is the Spring Data bean that tells auditing what time it is now. ShopLite's uses a clock fixed to Asia/Kolkata, so every audited LocalDateTime is India time.
A LocalDateTime has no zone, so LocalDateTime.now() gives the server's local time. Example 4 shows a setting that shifts India-time rows by hours.
Example 4 · hibernate.jdbc.time_zone: UTC on an India-time database
Runs in: the mapping-lab practice project (Spring Boot 4.1, Hibernate 7, the ShopLite MySQL database)
# Run the Order example from the Enums lesson again, with one extra line:spring: jpa: properties: hibernate.jdbc.time_zone: UTC # wrong for ShopLite# The runner saves an order with LocalDateTime.of(2026, 10, 16, 11, 42)# Then, in the mysql client:SELECT order_id, ordered_at FROM orders WHERE order_id IN (14, 17);Order 14: SHIPPED at 2026-09-22T02:35 New order 17: PLACED +----------+---------------------+ | order_id | ordered_at | +----------+---------------------+ | 14 | 2026-09-21 21:05:00 | | 17 | 2026-10-16 06:12:00 | +----------+---------------------+
What this code does
- Reading: Hibernate took the stored
21:05as UTC and converted it to the JVM's India time, so order 14 moved to 02:35 the next morning. - Writing:
11:42India time was converted to UTC and stored as06:12. The same setting that is right for a UTC database corrupts an India-time one, with no error. - Pick one rule per database and keep it everywhere. ShopLite's rule is India time in
DATETIME, so it has nojdbc.time_zoneline and uses an IndiaClockfor "now".
LocalDateTime.now() gives India time on your laptop and UTC on most cloud servers, so the zone must be decided once. A database default (DEFAULT CURRENT_TIMESTAMP) fills the column when an INSERT leaves it out and also covers rows inserted by SQL scripts; an app timestamp is set in Java and sent in the INSERT, so the object knows it at once. ShopLite keeps the default in the schema for scripts and sets the value from the app for every save, with Clock.system(ZoneId.of("Asia/Kolkata")) matching the contract.
Apps that store UTC instead set spring.jpa.properties.hibernate.jdbc.time_zone: UTC: Hibernate then converts between the JVM zone and UTC on every write and read, including LocalDateTime. Never add that line to ShopLite: its India-time rows would shift by 5 hours 30 minutes (Example 4).
A preview of @CreatedBy with AuditorAware
AuditorAware<T> is the Spring Data interface that answers who is acting now: its getCurrentAuditor() returns an Optional<T>. @CreatedBy and @LastModifiedBy fill fields from it.
@CreatedBy fills a field with the current user, the way @CreatedDate fills the time. Example 5 previews it with a fixed user.
Example 5 · Preview: @CreatedBy filled by an AuditorAware bean
Runs in: the mapping-lab practice project with a throwaway lab database (ddl-auto=create)
// src/main/java/com/shoplite/common/CurrentUserAuditor.javapackage com.shoplite.common;
import org.springframework.data.domain.AuditorAware;import org.springframework.stereotype.Component;
import java.util.Optional;
@Componentclass CurrentUserAuditor implements AuditorAware<String> {
@Override public Optional<String> getCurrentAuditor() { // Section 17 replaces this with the logged-in user's e-mail from Spring Security return Optional.of("system"); }}
// Added to AuditableEntity@CreatedBy@Column(name = "created_by", nullable = false, updatable = false, length = 255)private String createdBy;
Coupon fest = coupons.save(new Coupon("FEST20", 20));System.out.println(fest.getCode() + " created by " + fest.getCreatedBy() + " at " + fest.getCreatedAt());DEBUG ... org.hibernate.SQL : insert into coupons (code,created_at,created_by,percent_off,updated_at) values (?,?,?,?,?) FEST20 created by system at 2026-10-16T11:36:56
What this code does
- Spring Data found the one
AuditorAware<String>bean and called it before theINSERT, the same moment it asked theDateTimeProviderfor the time. - The type parameter matches the field:
AuditorAware<String>for aString createdBy. A user id would beAuditorAware<Integer>. - Section 17 changes only
getCurrentAuditor()to return the logged-in user, and returnsOptional.empty()for anonymous requests.
There is no login in ShopLite yet, so the preview returns a fixed "system". Section 17 (Spring Security) replaces that one method to read the logged-in user from the security context; no entity code changes.
ShopLite's tables have no created_by column today. Example 5 runs on the lab coupons table, and the real column arrives with a migration when Section 17 needs it.
Next step
Check your understanding
11 quick questions