是Spring Data Mongodb,如何在不通过ID的情况下从另一个文档引用一个文档

时间:2022-09-11 17:04:44

I'm using MongoDB with Spring Data. I'd like to have one document reference another (a user in fact), but I end up with having to do extra work. E.g.

我正在使用MongoDB和Spring Data。我希望有一个文档引用另一个(事实上是用户),但最终我不得不做额外的工作。例如。

class Watch {
    String id;
    User user;
}

That's nice, but I seem to end up with the whole user embedded in the document, so I do this:

这很好,但我似乎最终将整个用户嵌入到文档中,所以我这样做:

class Watch {
    String id;
    String userId;
}

But then I want to use it in some JSTL, and I want to do this:

但后来我想在一些JSTL中使用它,我想这样做:

${watch.user.email}

But I have to add some mapping code.

但我必须添加一些映射代码。

1 个解决方案

#1


5  

Use @DBRef annotation on user.

在用户上使用@DBRef注释。

You need to save user separately (no cascading), but you probably want to do that.

您需要单独保存用户(无级联),但您可能希望这样做。

Beware that user will be loaded eagerly.

请注意,用户将被急切地加载。

#1


5  

Use @DBRef annotation on user.

在用户上使用@DBRef注释。

You need to save user separately (no cascading), but you probably want to do that.

您需要单独保存用户(无级联),但您可能希望这样做。

Beware that user will be loaded eagerly.

请注意,用户将被急切地加载。