Spring Date And User Audit
@ MappedSuperclass
@ Data
@ EntityListeners (AuditingEntityListener .class )
@ JsonIgnoreProperties (
value = { "createdAt" , "updatedAt" },
allowGetters = true
)
public abstract class DateAudit implements Serializable {
private static final long serialVersionUID = 1L ;
@ CreatedDate
@ Column (name ="created_at" ,nullable = false , updatable = false )
private Instant createdAt ;
@ LastModifiedDate
@ Column (name = "updated_at" ,nullable = false )
private Instant updatedAt ;
}
@ EqualsAndHashCode (callSuper = true )
@ MappedSuperclass
@ Data
@ JsonIgnoreProperties (
value = { "createdBY" , "updatedBy" },
allowGetters = true
)
public abstract class UserDateAudit extends DateAudit {
private static final long serialVersionUID = 1L ;
@ CreatedBy
@ Column (name = "created_by" ,updatable = false )
private Long createdBy ;
@ LastModifiedBy
@ Column (name = "updated_by" )
private Long updatedBy ;
}
@ Configuration
@ EnableJpaAuditing
public class AuditingConfig {
@ Bean
public AuditorAware <Long > auditorProvider () {
return new SpringSecurityAuditAwareImpl ();
}
}
class SpringSecurityAuditAwareImpl implements AuditorAware <Long > {
@ Override
public Optional <Long > getCurrentAuditor () {
Authentication authentication = SecurityContextHolder .getContext ().getAuthentication ();
if (authentication == null || !authentication .isAuthenticated () || authentication instanceof AnonymousAuthenticationToken ) {
return Optional .empty ();
}
UserDetailsImpl userPrincipal = (UserDetailsImpl ) SecurityContextHolder .getContext ().getAuthentication ().getPrincipal ();
return Optional .ofNullable (userPrincipal .getId ());
}
}