java - MongoTemplate upsert - 从 pojo 进行更新的简单方法(哪个用户已编辑)?

标签 java mongodb upsert mongotemplate

这是一个简单的pojo:

public class Description {
    private String code;
    private String name;
    private String norwegian;
    private String english;
}

请参阅以下代码以通过 spring MongoTemplate 将 upsert 应用到 MongoDb:

Query query = new Query(Criteria.where("code").is(description.getCode()));
Update update = new Update().set("name", description.getName()).set("norwegian", description.getNorwegian()).set("english", description.getEnglish());
mongoTemplate.upsert(query, update, "descriptions");

生成 Update 对象的行手动指定 Item 类的每个字段。

但是如果我的 Item 对象发生变化,那么我的 Dao 层就会中断。

那么有没有办法避免这样做,以便我的 Item 类中的所有字段都自动应用于更新?

例如

Update update = new Update().fromObject(item);

请注意,我的 pojo 没有扩展 DBObject

最佳答案

我为这个问题找到了一个很好的解决方案

//make a new description here
Description d = new Description();
d.setCode("no");
d.setName("norwegian");
d.setNorwegian("norwegian");
d.setEnglish("english");

//build query
Query query = new Query(Criteria.where("code").is(description.getCode()));

//build update
DBObject dbDoc = new BasicDBObject();
mongoTemplate.getConverter().write(d, dbDoc); //it is the one spring use for convertions.
Update update = Update.fromDBObject(dbDoc);

//run it!
mongoTemplate.upsert(query, update, "descriptions");

请注意,Update.fromDBObject 返回一个包含 dbDoc 中所有字段的更新对象。如果你只想更新非空字段,你应该编写一个新方法来排除空字段。

例如,前端发布如下文档:

//make a new description here
Description d = new Description();
d.setCode("no");
d.setEnglish("norwegian");

我们只需要更新“语言”字段:

//return Update object
public static Update fromDBObjectExcludeNullFields(DBObject object) {
    Update update = new Update();       
    for (String key : object.keySet()) {
        Object value = object.get(key);
        if(value!=null){
            update.set(key, value);
        }
    }
    return update;
}

//build udpate
Update update = fromDBObjectExcludeNullFields(dbDoc);

关于java - MongoTemplate upsert - 从 pojo 进行更新的简单方法(哪个用户已编辑)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20001627/

相关文章:

python - 接受 POST 和 GET 的搜索屏幕

mongodb 副本集成员无法通过 SSL 加入集群

node.js - 如何在 Mongodb 的 Upsert 上自动更新时间戳

java - 使用 JPA 使用 native 查询填充 DTO

java - 在 Hazelcast 中构建 SqlPredicate 集合结果时出错

c++ - 将 mongocxx 连接到 mongodb 服务器 : SSL support not available 时出错

MongoDB 集合更新 : initialize a document with default values

java - 无法访问 View 以更改背景颜色

java - Android 查找部分匹配的数组索引值

mongodb - MongoDB 中的批量更新/更新插入?