我有像
这样的模型类public class MyClass extends ReflectionDBObject {
private List<NiceAttribute> attributes;
...
}
public class NiceAttribute extends ReflectionDBObject {
...
}
我以类型安全的方式创建它,比如
List<NiceAttribute> attrs = new ArrayList<NiceAttribute>();
attrs.add(new NiceAttribute());
MyClass myClass = new MyClass();
myClass.setAttributes(attrs);
然后将其保存到mongo,并使用类似
的代码进行检索DBCollection col = ...;
col.setObjectClass(MyClass.class)
MyClass foundObject = (MyClass)col.findOne();
但问题是foundObject
的{{1}}成为attributes
的列表。看起来驱动程序不能(或不想)检测列表项类型。这是司机限制,还是我错过了什么?这个问题的优雅解决方法是什么?
答案 0 :(得分:4)
嗯,有一个解决方案,但你不会喜欢它。基本上,您可以为对象中的内部路径指定相应的类。这就是我所做的,它的确有效:
public class Release extends ReflectionDBObject {
//other fields omitted
private List<ReleaseDetailsByTerritory> releaseDetailsByTerritory = new ArrayList<ReleaseDetailsByTerritory>();
}
public class ReleaseDetailsByTerritory extends ReflectionDBObject { //...}
现在,如果我只是这样做:
releaseColl.setObjectClass(Release.class);
releaseColl.setInternalClass("ReleaseDetailsByTerritory.0", ReleaseDetailsByTerritory.class);
Release r = (Release) releaseColl.findOne();
//the internal list will contain ReleaseDetailsByTerritory type objects (not DBObjects)
System.out.println(r.getReleaseDetailsByTerritory().get(0).getClass().getName());
这里糟糕的事情是你不能(或者至少我没有找到)如何为嵌入式数组的所有元素指定映射类。你做不了类似的事情:
releaseColl.setInternalClass("ReleaseDetailsByTerritory", ReleaseDetailsByTerritory.class);
或
releaseColl.setInternalClass("ReleaseDetailsByTerritory.*", ReleaseDetailsByTerritory.class);
您可以指定嵌入数组的任何可能元素的映射类:
releaseColl.setInternalClass("ReleaseDetailsByTerritory.0", ReleaseDetailsByTerritory.class);
releaseColl.setInternalClass("ReleaseDetailsByTerritory.1", ReleaseDetailsByTerritory.class);
releaseColl.setInternalClass("ReleaseDetailsByTerritory.2", ReleaseDetailsByTerritory.class);
答案 1 :(得分:-1)
你应该使用Morphia。它增加了对POJO和嵌入对象(和集合)的支持。它没有任何限制驱动程序要求您的类看起来像Map<String, Object>
。