简体   繁体   English

Spring Mongodb-插入嵌套文档?

[英]Spring Mongodb - Insert Nested document?

I have the following classes 我有以下课程

@Document
public class PersonWrapper {

    @Id
    private ObjectId _Id;

    @DBRef
    private Person person

    // Getters and setters removed for brevity.
}

public class Person
{
    @Id
    private ObjectId _Id;

    private String name;

    // Getters and setters removed for brevity.
}

And - I have the following MongoReposityClass... 而且-我有以下MongoReposityClass ...

public interface PersonWrapperRepository extends MongoRepository<Person, String> {
    Person findByPerson_name(String name);
}

Showing the repository class may have been pointless - but basically what I do here is create an instance of the repository class and then I create a PersonWrapper object, then do something like : 显示存储库类可能没有意义-但基本上我在这里要做的是创建存储库类的实例,然后创建一个PersonWrapper对象,然后执行以下操作:

repo.insert(personWrapperInstance);

Now, while this will infact work - I find that I need to insert "Person" first, and then add the returned object to the PersonWrapper, then do another insert. 现在,尽管这实际上可以正常工作-我发现我需要先插入“ Person”,然后将返回的对象添加到PersonWrapper,然后再进行一次插入。

That is fine and all, and I am sure I can write some flow control to catch errors and behave sensibly if something breaks. 很好,一切都很好,我确信我可以编写一些流控制来捕获错误,并在出现故障时做出明智的举动。

HOWEVER - Everyone knows that would be inefficient, because it is two calls to save. 但是-每个人都知道这样做效率不高,因为要保存是两个调用。 There has GOT to be a way I can basically create the nested objects, and do an insert on the ParentWrapper, and have mongo insert the Person instance if it doesn't already exist, right? 有一种GOT可以让我基本上创建嵌套的对象,并在ParentWrapper上进行插入,并让mongo插入Person实例(如果尚不存在),对吗?

I have been googled this, but ran into some issues getting what I wanted to know. 我一直在用Google搜索,但是遇到了一些我想知道的问题。

This cannot be done with spring-data-mongodb. 使用spring-data-mongodb无法做到这一点。 The Framework lacks the ability to work with nested objects, and your way of putting it in a try catch is pretty much the only way to do it. 该框架缺乏使用嵌套对象的能力,而将其放入try catch的方法几乎是唯一的方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM