从文档链接@DocumentReference访问对象时Spring数据反应式MongoDB空引用

问题描述 投票:0回答:2

我需要你的帮助。我正在使用 Spring 反应式 (WebFlux) 和 mongoDB 也是反应式的。

在我的模型中,我有两个实体的关联:UserPost。对问题进行建模,1 个用户有一个关联帖子列表(一对多参考),根据下面的示例:

@Document(collection = "user")
public class User {
    
    @Id
    private String id;
    private String name;
    private String email;
    
    @DocumentReference(lazy = true)
    private List<Post> posts;
@Document(collection = "post")
public class Post {

    @Id
    private String id;
    private Instant date;
    private String title;
    private String body;

我正在为数据库做种,并包含一个User和一个关联的Posts数组,如下图所示:

https://drive.google.com/file/d/1Z72me8Ga9K6MNaFxv4A1sT801K6zzC_J/view?usp=share_link

问题是当我尝试访问与用户关联的列表时。当我找到用户的所有帖子时,返回的对象始终带有空引用。

下面是我调用 findPosts 来获取 List 的方法,它返回空对象引用。

public Flux<PostDTO> findPosts(String id) {
    return repository.findById(id)
            .flatMapMany(existingUser -> {
        if (existingUser.getPosts().isEmpty())
           Flux.empty();
                List<PostDTO> list = existingUser.getPosts()
                                     .stream().map(x -> new PostDTO(x)).toList();
        return Flux.fromIterable(list);
         })
         .switchIfEmpty(Mono.error(new ResourceNotFoundException("Recurso não encontrado")));
}

java.lang.NullPointerException:无法调用“java.util.List.isEmpty()”,因为“com.devsuperior.workshopmongo.entities.User.getPosts()”的返回值为null

在stackoverflow上寻找这个问题,我看到了一些没有答案的问题,根据示例和整个互联网,使用实体关联的示例很少。

Spring Data MongoDB 无法加载参考集合(@DocumentReference)

如何在Spring Data MongoDB中使用@DocumentReference获取重复数据?

您可以通过提示甚至类似的示例来帮助我吗?

mongodb spring-webflux spring-data-mongodb-reactive
2个回答
2
投票

我被同样的问题困扰了几天,直到我说服自己应该阅读手册,然后我找到了它。 :'(

https://docs.spring.io/spring-data/mongodb/docs/current/reference/html/#mapping-usage.document-references

不支持使用响应式读取文档参考 基础设施。


0
投票

您可以通过以下语法获取惰性对象:

List<Post> posts = (List<Post>) ((LazyLoadingProxy) existingUser.getPosts()).getTarget();

然后进一步处理。

© www.soinside.com 2019 - 2024. All rights reserved.