我有一个简单的问题,将实体的嵌入式集合存储和检索到 mongo。我已经检查了这些问题:
我的理解是保存一个列表对象,该对象的类必须扩展ReflactionDBObject。这适用于保存对象,通过使用嵌入式集合检索它不起作用。
这里有一个简单的测试表明检索嵌入式实体不起作用!
@Test
public void whatWasStoredAsEmbeddedCollectionIsRetrieved2() {
BasicDBObject country = new BasicDBObject();
country.put("name", "Bulgaria");
List<City> cities = Lists.newArrayList(new City("Tarnovo"));
country.put("listOfCities", cities);
DBCollection collection = db().get().getCollection("test_Collection");
collection.save(country);
DBCursor object = collection.find(new BasicDBObject().append("name", "Bulgaria"));
DBObject returnedCity = object.next();
DBObject embeddedCities = (DBObject) returnedCity.get("listOfCities");
System.out.println(embeddedCities);
}
这里是城市班
class City extends ReflectionDBObject {
String name;
City() {
}
City(String name) {
this.name = name;
}
public String getName() {
return name;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof City)) return false;
City city = (City) o;
if (name != null ? !name.equals(city.name) : city.name != null) return false;
return true;
}
@Override
public int hashCode() {
return name != null ? name.hashCode() : 0;
}
@Override
public String toString() {
return "City{" +
"name='" + name + '\'' +
'}';
}
}
System.out.println 语句的输出is [ { "_id" : null }]
现在如何取回嵌入的对象和其中的嵌入列表?