我正在尝试在 Spring MongoDB 中创建手动引用以简单地将 ObjectId 存储在引用字段中并仅在需要时填充它。 (即没有 DBRef)
但是,我一直无法找到有关如何正确实现这一点的文档。
假设我有一个像这样的简单模型:
@Document(collection = "person")
public class Person{
@Id
private String id;
... other attributes
//This is a reference to Address model
private ObjectId address;
}
和@Document(collection = "address")
public class Address{
@Id
private String id;
... other attributes
}
如何在此处创建手动引用以仅将地址模型的 ID 存储在 Person 中,然后仅在需要时填充?更新:
澄清一下,我们已经有很多以前使用 Mongoose 插入的数据库文档,其中模型 A 包含引用模型 B 的 ObjectId。使用 mongoose 我们可以调用
.populate
需要时在这些上。然后当我们保存文档时,Mongoose 只保存了 ObjectId。基本上我试图在 Spring 中实现一个类似的系统。
我创建了一个自定义转换器,在加载数据时将 ObjectId 转换为特定类型,但此解决方案没有帮助,因为它不会在保存时将模型转换为 ObjectId。
这是我们需要的:
同样,这正是 Javascript 中 Mongoose 的工作方式,这也是我们目前正在使用的。
我正在寻找详细的答案或某种教程来解释如何实现这一点,因为我无法找到任何使用手动引用的示例,这很奇怪,因为手动引用是更流行和推荐的方式这样做。
最佳答案
使用@DbRef 和相同的字段名称只是将 ObjectId 列表引用为模型上的另一个字段。
public class ModelModelListener extends AbstractMongoEventListener<Model> {
@Override
public void onBeforeSave(BeforeSaveEvent<Model> event) {
final Model source = event.getSource();
final Document document = event.getDocument();
final List<Model> modelList = source.getModelList();
final List<ObjectId> modelIdList = source.getModelIdList();
if (document != null)
document.put("modelList", modelList != null ? toIdList(modelList) : modelIdList);
}
@Override
public void onAfterConvert(AfterConvertEvent<Model> event) {
final Model source = event.getSource();
final Document document = event.getDocument();
if (document != null)
source.setModelIdList(document.getList("modelList", ObjectId.class));
}
}
@Data // Lombok getter setter
@Document
public class Model {
@Field("modelList")
@DBRef(lazy = true)
private List<Model> modelList;
@Field
private List<ObjectId> modelIdList;
}
或者,您可以在更新或插入时使用带有条件的 MongoTemplate。final Update update = new Update();
update.push("field", modelB.getId());
mongoTemplate.updateFirst(query, update, ModelA.class);
关于java - Spring MongoDB 手册引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64163644/