Spring Mongodb - 插入嵌套文档? [英] Spring Mongodb - Insert Nested document?

查看:81
本文介绍了Spring Mongodb - 插入嵌套文档?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下课程

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

而且 - 我有以下 MongoReposityClass...

And - I have the following MongoReposityClass...

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

显示存储库类可能毫无意义 - 但基本上我在这里做的是创建存储库类的实例,然后创建一个 PersonWrapper 对象,然后执行以下操作:

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);

现在,虽然这实际上会起作用 - 我发现我需要先插入Person",然后将返回的对象添加到 PersonWrapper,然后再进行一次插入.

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.

然而 - 每个人都知道这会效率低下,因为它是两个保存调用.有一种方法我可以基本上创建嵌套对象,并在 ParentWrapper 上进行插入,如果 Person 实例尚不存在,则让 mongo 插入它,对吗?

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.

推荐答案

spring-data-mongodb 无法做到这一点.框架缺乏处理嵌套对象的能力,您将它放入 try catch 的方式几乎是唯一的方法.

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.

这篇关于Spring Mongodb - 插入嵌套文档?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆