Configure Spring Audit
In order to track when our entities are created and updated, we need to enable Spring JPA's auditing functionality to automatically maintain audit fields like @CreatedDate and @LastModifiedDate.
Enable JPA Auditing
Spring JPA auditing allows us to automatically track when entities are created and modified, but it needs to be explicitly enabled.
We'll enable it globally for our application with two key components:
- A configuration class with the
@EnableJpaAuditingannotation - An
orm.xmlconfiguration file that registers the auditing entity listener
Here's how we implement the configuration class:
@Configuration
@EnableJpaAuditing
public class JpaConfiguration {
}Next, we need to create the orm.xml file in a specific location:
<?xml version="1.0" encoding="UTF-8"?>
<entity-mappings xmlns="http://java.sun.com/xml/ns/persistence/orm"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence/orm http://java.sun.com/xml/ns/persistence/orm_2_0.xsd"
version="2.0">
<persistence-unit-metadata>
<persistence-unit-defaults>
<entity-listeners>
<entity-listener class="org.springframework.data.jpa.domain.support.AuditingEntityListener"/>
</entity-listeners>
</persistence-unit-defaults>
</persistence-unit-metadata>
</entity-mappings>The orm.xml file needs to be placed in the src/main/resources/META-INF directory. When the application is built, this file will be included in the final package and made available to Hibernate.
Why Global Configuration?
While we could add the @EntityListeners annotation to each entity class individually, using global configuration through orm.xml is a better approach because:
- It reduces code duplication
- It makes the auditing behavior consistent across all entities
- It's easier to maintain and modify in one central location
Summary
- Created
JpaConfigurationclass with the@EnableJpaAuditingannotation - Added
orm.xmlconfiguration file enabling the audit fields