Issue
I am using Spring Mongo Auditing and @CreatedDate @CreatedBy not working but @LastModifiedDate and @LastModifiedBy working fine.
I added @EnableMongoAuditing on a configuration class and also defined the AuditAware.
@Component("securityAuditorAware")
public class SecurityAuditorAware implements AuditorAware<String> {
@Override
public Optional<String> getCurrentAuditor() {
return Optional.ofNullable(SecurityUtils.getUserPrincipal()).map(AuthenticatedUser::getIssuer);
}
}
Auditing class is :
@Document
public class Template {
@Id
private UUID id = UUID.randomUUID();
@CreatedDate
private Date createdOn;
@LastModifiedDate
private Date modifiedOn;
@CreatedBy
private String createdBy;
@LastModifiedBy
private String modifiedBy;
}
When I save the document it put null in both createdOn and createdBy but the right values in both modifiedOn and modifiedBy
Thanks for the help
Solution
If your Entity does not inheritance Persistable
interface, you should define a field which marked by @Version
(org.springframework.data.annotation.Version).
@Document
public class Template {
@Id
private UUID id = UUID.randomUUID();
@CreatedDate
private Date createdOn;
@LastModifiedDate
private Date modifiedOn;
@CreatedBy
private String createdBy;
@LastModifiedBy
private String modifiedBy;
@Version
private Integer version;
}
In other side, if your entity inheritance Persistable
interface, you should implement logical which to detect the entity never been persisted before.
For more information, you can check two class: PersistentEntityIsNewStrategy
and PersistableIsNewStrategy
Answered By - Cường Lư Quốc
Answer Checked By - Mary Flores (JavaFixing Volunteer)