I am trying to apply the auditing for update and delete operation using spring data MongoDB. For the add operation, I have the below model to find the addition in the database, which is working perfectly.
public class Audit {
@CreatedBy
private String CreatedBy;
@CreatedDate
private Instant createdDate;
@LastModifiedBy
private String lastModifiedUser;
@LastModifiedDate
private Instant lastModifiedDate;
}
How do I maintain the history for update and delete operation? I know there is a lifecycle hook for mongoDb in spring data
@Component
@EnableMongoAuditing
public class GenericAuditing extends AbstractMongoEventListener<Object> {
private MongoTemplate mongoTemplate;
private static final Logger LOG = LoggerFactory.getLogger(GenericAuditing.class);
public GenericAuditing(MongoTemplate mongoTemplate) {
this.mongoTemplate = mongoTemplate;
}
@Override
public void onAfterSave(AfterSaveEvent<Object> event) {
LOG.info("On After Save inserting the record to the Delete and update collection");
}
@Override
public void onAfterDelete(AfterDeleteEvent<Object> event) {
LOG.info("On After delete inserting the record to the Delete and update collection");
Object obj = event.getSource();
DeleteUpdateAudit deleteUpdateAudit = new DeleteUpdateAudit(obj, DatabaseAction.DELETE);
this.mongoTemplate.insert(deleteUpdateAudit);
}
}
How do I identify the onAfterSave is for Save or update. Since that method is called for both save and update operation. What is the best approach for auditing DELETE and UPDATE operation