这是一个简单的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/