[英]Spring MongoDB data can not fetch @DBRef objects with “find” query
有一个对象是经典的POJO,如下所示:
@Document
public class MyPojo {
@DBRef
@Field("otherPojo")
private List<OtherPojo> otherPojos;
}
和OtherPojo.java
:
public class OtherPojo{
@Id
private ObjectId _id;
private String someOtherFields;
}
我不能级联保存这些,但我通过首先保存DBRefs然后保存我的POJO列表来克服它,但仍然当我尝试获取所有列表或使用以下代码查询其中一些时:
Query query = new Query( Criteria.where( "myPojo.blabla" ).is( "blabla" ) );
List<MyPojo> resultList = mongoTemplate.find( query, MyPojo.class, "myCollection" );
它返回一个null DBrefs列表,它计为true。 例如:保存了10个DBRef,它返回10个空对象,但其原始类型和其他不是DBRref的类型都是非空的。 我怎么处理这个?
我保存我的对象如下:
for (MyPojo pojo : somePojoList) {
for (OtherPojo otherPojo : pojo.getOtherPojos()) {
mongoTemplate.save(otherPojo, "myCollection");
}
}
// ...
mongoTemplate.insert( myPojoList, "myCollection" );
编辑:好的,现在我知道如果我在保存otherPojos时没有指定集合名称,我可以获取它们(感谢@ jmen7070)。 但我必须在那里写myCollection,因为我总是掉线并重新创建它们。 这是一个用例。 那么我怎么能说“找到使用相同集合来获取DBRefs的方法”呢?
正如您从文档中看到的那样:
映射框架不处理级联保存。 如果更改Person对象引用的Account对象,则必须单独保存Account对象。 调用Person对象上的save不会自动将Account对象保存在属性帐户中。
因此,首先,您必须保存otherPojos列表的每个对象。 之后,您可以保存MyPojo实例:
MyPojo pojo = new MyPojo();
OtherPojo otherPojo = new OtherPojo();
OtherPojo otherPojo1 = new OtherPojo();
pojo.setOtherPojos(Arrays.asList(otherPojo, otherPojo1));
mongoTemplate.save(otherPojo);
mongoTemplate.save(otherPojo1);
mongoTemplate.save(pojo);
更新:您保存了一个对象:
for( MyPojo pojo : somePojoList ){
for( OtherPojo otherPojo : pojo.getOtherPojos() ){
mongoTemplate.save( otherPojo,collectionname );
}
}
所有otherPojo对象都将保存在名为“collectionName”的集合中。
但是你的myPojo对象有一个$ ref到otherPojo集合..
"otherPojo" : [
{
"$ref" : "otherPojo",
"$id" : ObjectId("535f9100ad52e59815755cef")
},
{
"$ref" : "otherPojo",
"$id" : ObjectId("535f9101ad52e59815755cf0")
}
]
所以,“collectionname”变量
mongoTemplate.save( otherPojo,collectionname );
必须是“otherPojo”。
为避免混淆,我建议使用@Doucument注释指定用于保存OtherPojo对象的集合:
@Document(collection="otherPojos")
public class OtherPojo{
@Id
private ObjectId _id;
private String someOtherFields;
}
并使用mongoTemplate的重载save()方法保存otherPojo对象
mongoTemplate.save( otherPojo );
这样,myPojo文档就会有一个有效的$ ref
更新2:
在这种情况下,您希望将父对象和子对象存储在同一集合中。
为此,您可以使用此方法
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.