从 Spring/MongoDB findAndModify 返回旧实体和新实体 [英] Returning both old and new entities from Spring/MongoDB findAndModify

查看:45
本文介绍了从 Spring/MongoDB findAndModify 返回旧实体和新实体的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们通过 Spring Data 使用 MongoDB,并依靠 findAndModify 操作来更新现有实体或创建新实体.

We're using MongoDB via Spring Data and rely on the findAndModify operation to update existing entities or create new ones.

findAndModify 中,我们可以使用 returnNew(...) 配置返回实体的旧状态或新状态.

In the findAndModify we can configure to return old state of the entity or the new one using returnNew(...).

有没有办法从 findAndModify 返回旧实体和新实体?

Is there some way to return both old and new entities from findAndModify?

我们需要比较更新前后的实体状态,这就是我们需要两个实例的原因.

We need to compare entity states before and after update, this is why we need both instances.

目前我们使用 requireNew(false) 然后手动更新旧实例的副本,如下所示:

At the moment we're resorting to requireNew(false) and then manually update a copy of the old instance, something like this:

public Pair<Data> saveItems(String id, List<Item> items) {
    final Query findById = ...;

    final Update update = new Update();
    // This is what we actually update
    update.set(ENTITY_FIELD_ITEMS, newItems);
    update.inc(ENTITY_FIELD_VERSION, 1);
    // Try updating and return the old data 
    final Data oldData = operations.findAndModify(findById, update,
        FindAndModifyOptions.options().upsert(true).returnNew(false), Data.class);

    // Copy or create new instance
    final Data newData;
    if (oldData == null) {
        newData = new Data(id);
    }
    else {
        newData = new Data(oldData);
    }
    // Apply the same update
    newData.setItems(newItems);
    newData.incVersion();
    return new Pair<Data>(oldData, newData);
}

工作但不是很漂亮,因为我们必须重做我们在旧实例副本上的 Update 中已经做过的事情.

Works but isn't pretty as we have to redo the same things we already do in the Update on the copy of the old instance.

我们还考虑过首先加载旧实例并运行更新,但这并不安全,因为实体可能在加载和更新之间已被修改.这可以通过版本和乐观锁定来解决,但这会使事情变得更加复杂.

What we've also considered was first loading an old instance and the running the update but it's not safe as the entity may have been modified between the load and the update. This may be addressed with versions and optimistic locking, but that makes things even more complicated.

推荐答案

有没有办法从 findAndModify 中同时返回旧实体和新实体?

Is there some way to return both old and new entities from findAndModify?

,无法使用 findAndModify.

No, there's no way to return both old and new value with findAndModify.

这篇关于从 Spring/MongoDB findAndModify 返回旧实体和新实体的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆