Spring MongoDB数据无法使用"find"查询获取@DBRef对象

Ser*_*mir 5 java spring mongodb spring-data-mongodb

有一个对象是经典的POJO,如下所示:

@Document
public class MyPojo {
  @DBRef
  @Field("otherPojo")
  private List<OtherPojo> otherPojos;
}
Run Code Online (Sandbox Code Playgroud)

而且OtherPojo.java:

public class OtherPojo{
  @Id
  private ObjectId _id;
  private String someOtherFields;
}
Run Code Online (Sandbox Code Playgroud)

我不能级联保存这些,但我通过首先保存DBRefs然后保存我的POJO列表来克服它,但仍然当我尝试获取所有列表或使用以下代码查询其中一些时:

Query query = new Query( Criteria.where( "myPojo.blabla" ).is( "blabla" ) );
List<MyPojo> resultList = mongoTemplate.find( query, MyPojo.class, "myCollection" );
Run Code Online (Sandbox Code Playgroud)

它返回一个null DBrefs列表,它计为true.例如:保存了10个DBRef,它返回10个空对象,但其原始类型和其他不是DBRref的类型都是非空的.我怎么处理这个?

我保存我的对象如下:

for (MyPojo pojo : somePojoList) {
    for (OtherPojo otherPojo : pojo.getOtherPojos()) {
        mongoTemplate.save(otherPojo, "myCollection");
    }
}

// ...

mongoTemplate.insert( myPojoList, "myCollection" );
Run Code Online (Sandbox Code Playgroud)

编辑:好的,现在我知道如果我在保存otherPojos时没有指定集合名称,我可以获取它们(感谢@ jmen7070).但我必须在那里写myCollection,因为我总是掉线并重新创建它们.这是一个用例.那么我怎么能说"找到使用相同集合来获取DBRefs的方法"呢?

jme*_*070 2

正如您从文档中看到的:

映射框架不处理级联保存。如果更改 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);
Run Code Online (Sandbox Code Playgroud)

更新: 您保存了一个对象:

for( MyPojo pojo : somePojoList ){
            for( OtherPojo otherPojo : pojo.getOtherPojos() ){
                mongoTemplate.save( otherPojo,collectionname );
            }
        }
Run Code Online (Sandbox Code Playgroud)

所有其他Pojo对象将保存在名为“collectionName”的集合中。

但是你的 myPojo 对象有一个指向 otherPojo 集合的 $ref 。

"otherPojo" : [ 
        {
            "$ref" : "otherPojo",
            "$id" : ObjectId("535f9100ad52e59815755cef")
        }, 
        {
            "$ref" : "otherPojo",
            "$id" : ObjectId("535f9101ad52e59815755cf0")
        }
    ]
Run Code Online (Sandbox Code Playgroud)

所以,“collectionname”变量

 mongoTemplate.save( otherPojo,collectionname );
Run Code Online (Sandbox Code Playgroud)

必须是“otherPojo”。

为了避免混淆,我建议使用 @Doucument 注解指定一个用于保存 OtherPojo 对象的集合:

@Document(collection="otherPojos")
public class OtherPojo{

@Id
private ObjectId _id;
private String someOtherFields;

}
Run Code Online (Sandbox Code Playgroud)

并使用 mongoTemplate 的重载 save() 方法来保存 otherPojo 对象

mongoTemplate.save( otherPojo );
Run Code Online (Sandbox Code Playgroud)

这样,您将获得 myPojo 文档的有效 $ref

更新2:

在这种情况下,您希望将父对象和子对象存储在同一个集合中。

为了实现这一点,您可以使用这种方法