Spring Mongodb - Insert Nested document?

大憨熊 提交于 2019-12-12 06:21:58

问题


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...

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 :

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.

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?

I have been googled this, but ran into some issues getting what I wanted to know.


回答1:


This cannot be done with 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.



来源:https://stackoverflow.com/questions/43552583/spring-mongodb-insert-nested-document

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!