AbstractMongoEventListener to identify update or add event spring boot mongoDb

Viewed 1180

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

2 Answers

With regard to identifying save or update, you could check the Document in the AfterSaveEvent. If it has an _id then it's an update:

    @Override
    public void onAfterSave(AfterSaveEvent<Object> event) {
        LOG.info("On After Save inserting the record to the Delete and update collection");
        
        boolean isUpdate = event.getDocument().containsKey("_id");
        if (isUpdate) {
            // add your specific update logic here
        } else {
            // add your specific insert logic
        }
    }

You can get from the event the creationTime and the lastUpdate. If the are equals, it's a save

    @Override
    public void onAfterSave(AfterSaveEvent<User> event) {
        Date creationTime = event.getDocument().getDate("creationTime");
        Date lastUpdated = event.getDocument().getDate("lastUpdated");

        if (creationTime.equals(lastUpdated)) {
            // SAVE
        } else {
            // UPDATE
        }
    }
Related