这是一个简单的 pojo:
public class Description {
private String code;
private String name;
private String norwegian;
private String english;
}
请参阅以下代码来应用upsert
通过 spring MongoTemplate 到 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
类会自动应用于更新吗?
E.g.
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);
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)