AbstractMongoEventListener 识别更新或添加事件 spring boot mongoDb

Posted

技术标签:

【中文标题】AbstractMongoEventListener 识别更新或添加事件 spring boot mongoDb【英文标题】:AbstractMongoEventListener to identify update or add event spring boot mongoDb 【发布时间】:2020-12-24 10:47:40 【问题描述】:

我正在尝试使用 Spring Data MongoDB 应用审计以进行更新和删除操作。对于加法操作,我有以下模型在数据库中查找加法,效果很好。

public class Audit 
    @CreatedBy
    private String CreatedBy;

    @CreatedDate
    private Instant createdDate;

    @LastModifiedBy
    private String lastModifiedUser;

    @LastModifiedDate
    private Instant lastModifiedDate;

如何维护更新和删除操作的历史记录?我知道spring数据中有一个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 操作的最佳方法是什么

【问题讨论】:

【参考方案1】:

关于识别保存或更新,您可以查看AfterSaveEvent中的Document。如果它有一个_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
        
    

【讨论】:

【参考方案2】:

您可以从事件中获取 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
        
    

【讨论】:

以上是关于AbstractMongoEventListener 识别更新或添加事件 spring boot mongoDb的主要内容,如果未能解决你的问题,请参考以下文章