我一直在使用MongoInputFormat,它允许将MongoDB集合中的所有文档都放在用Hadoop编写的MapReduce作业中。
正如您在提供的示例中所看到的那样(this,this和this),提供给映射器的文档类型为BSONObject( Java中的接口。)
现在我也非常喜欢Morphia,它允许将MongoDB中的原始数据映射到更容易使用的POJO。
由于我只能将BSONObject作为输入,所以我考虑使用Morphia wiki this page底部描述的方法:
BlogEntry blogEntry = morphia.fromDBObject(BlogEntry.class, blogEntryDbObj);
我的问题是此方法需要DBObject而不是BSONObject。 DBObject实际上是:
public interface DBObject extends BSONObject
因为你可以看到我不能简单地从BSONObject转换为DBObject并调用提供的方法。
我如何以最好的方式处理这个问题?
答案 0 :(得分:1)
您会注意到BSONObject
和DBObject
接口非常相似。仅仅因为转换不存在并不意味着创建一个微不足道的东西并不容易:
class BSONDBObject extends BasicBSONObject implements DBObject {
boolean ispartial = false;
public BSONDBObject(BSONObject source) {
this.putAll(source);
}
public boolean isPartialObject() {
return ispartial;
}
public void markAsPartialObject() {
this.ispartial = true;
}
}
现在,您只需要
BSONObject bson; // Filled by the MongoInputFormat
BSONBDObject dbo = BSONDBObject(bson);
EntityCache = entityCache = new DefaultEntityCache();
BlogEntry blogEntry = morphia().fromDBObject(BlogEntry.class, dbo, entityCache);
答案 1 :(得分:-1)
我找到了一个适合我的解决方案:
实际上我现在有这样的事情:
BSONObject bson; // Filled by the MongoInputFormat
EntityCache = entityCache = new DefaultEntityCache();
String json = JSON.serialize(bson)
DBObject dbObject = (DBObject) JSON.parse(json);
BlogEntry blogEntry = morphia().fromDBObject(BlogEntry.class, dbObject, entityCache);