For those whose want created or modified user detail along with the time using JPA and Spring Data can follow this. You can add @CreatedDate
,@LastModifiedDate
,@CreatedBy
and @LastModifiedBy
in the base domain. Mark the base domain with @MappedSuperclass
and @EntityListeners(AuditingEntityListener.class)
like shown below:
@MappedSuperclass
@EntityListeners(AuditingEntityListener.class)
public class BaseDomain implements Serializable {
@CreatedDate
private Date createdOn;
@LastModifiedDate
private Date modifiedOn;
@CreatedBy
private String createdBy;
@LastModifiedBy
private String modifiedBy;
}
Since we marked the base domain with AuditingEntityListener
we can tell JPA about currently logged in user. So we need to provide an implementation of AuditorAware and override getCurrentAuditor()
method. And inside getCurrentAuditor()
we need to return the currently authorized user Id.
public class AuditorAwareImpl implements AuditorAware<String> {
@Override
public Optional<String> getCurrentAuditor() {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
return authentication == null ? Optional.empty() : Optional.ofNullable(authentication.getName());
}
}
In the above code if Optional
is not working you may using older spring data. In that case try changing Optional
with String
.
Now for enabling the above Audtior implementation use the code below
@Configuration
@EnableJpaAuditing(auditorAwareRef = "auditorAware")
public class JpaConfig {
@Bean
public AuditorAware<String> auditorAware() {
return new AuditorAwareImpl();
}
}
Now you can extend the BaseDomain
class to all of your entity class where you want the created and modified date & time along with user Id