Saving the creation/modification timestamp of database records plays vital role in production applications. That helps in diagnosing issues and events.

If you're using Spring Data JPA, it's not a big deal. It's officially documented here. Below are the precise steps.

1) Add/edit orm.xml

Create orm.xml (at src/main/resources/META-INF/orm.xml) if you don't already have it. Then, add auditing configuration to it, looking as below:

<?xml version="1.0" encoding="UTF-8"?> <entity-mappings xmlns="" xmlns:xsi="" xsi:schemaLocation="" version="2.0"> <description>JPA</description> <persistence-unit-metadata> <persistence-unit-defaults> <entity-listeners> <entity-listener class=""/> </entity-listeners> </persistence-unit-defaults> </persistence-unit-metadata> </entity-mappings>

2) Annotate one of your configuration classes with @EnableJpaAuditing

For example

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

3) Add annotated fields to entity classes


@Entity public class Car { ... @CreatedBy private Integer createdById; @CreatedDate @Temporal(TemporalType.TIMESTAMP) private Date createdDate; @LastModifiedBy private Integer lastModifiedById; @LastModifiedDate @Temporal(TemporalType.TIMESTAMP) private Date lastModifiedDate; ...

Of course, you can create a super class containing all above fields. Don't forget to annotate that with @MappedSuperclass.

4) Configure an AuditorAware bean

Spring Data JPA will need you to provide an AuditorAware bean, which is used for getting the logged in user ID. An implementation can look as below:

@Component public class MyAuditorAware implements AuditorAware<Integer> { @Override public Optional<Integer> currentUser() { // return current user ID } }

That's all you need to store auditing information in your entities!