AbstractMongoEventListener来标识更新或添加事件,春季启动mongoDb

问题描述

我正在尝试使用spring数据MongoDB将审核应用于更新和删除操作。对于添加操作,我使用下面的模型在数据库中找到添加项,它运行良好。

public class Audit {
    @CreatedBy
    private String CreatedBy;

    @CreatedDate
    private Instant createdDate;

    @LastModifiedBy
    private String lastModifiedUser;

    @LastModifiedDate
    private Instant lastModifiedDate;
}

如何维护更新和删除操作的历史记录?我知道在春季数据中有mongoDb的生命周期挂钩

@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);
    }
}

如何确定onAfterSave用于保存或更新。由于该方法同时用于保存和更新操作。审核DELETE和UPDATE操作的最佳方法是什么

解决方法

关于识别保存或更新,您可以检查 Document 中的 AfterSaveEvent。如果它有 _id 那么它是一个更新:

    @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
        }
    }
,

您可以从事件中获取creationTime 和lastUpdate。如果相等,则保存

    @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
        }
    }